package com.fowo.api.service.impl;

import cn.hutool.core.collection.BoundedPriorityQueue;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.costAccounting.mapper.CommonCostingMapper;
import com.fowo.api.datainterface.constants.RequestMethodKind;
import com.fowo.api.datainterface.util.RedisUtil;
import com.fowo.api.datainterface.util.RestUtilLingXing;
import com.fowo.api.entity.*;
import com.fowo.api.inventory.entity.Inventory;
import com.fowo.api.inventory.entity.InventoryPlacement;
import com.fowo.api.inventory.model.InventoryStorageVo;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.*;
import com.fowo.api.model.adjustment.order.AdjustmentOrderVo;
import com.fowo.api.model.adjustment.order.product.AdjustmentOrderProductItemVo;
import com.fowo.api.model.classify.ClassifyVo;
import com.fowo.api.model.fbainvoice.FBAInvoiceVo;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailItemVo;
import com.fowo.api.model.inventory.list.InventoryListVo;
import com.fowo.api.model.inventory.list.subtable.InventoryListSubtableItemVo;
import com.fowo.api.model.lingxing.ListingFatherTemp;
import com.fowo.api.model.product.ProductVo;
import com.fowo.api.model.requisition.product.RequisitionProductItemVo;
import com.fowo.api.model.requisition.RequisitionVo;
import com.fowo.api.model.sales.outbound.SalesOutboundVo;
import com.fowo.api.model.shop.info.ShopInfoVo;
import com.fowo.api.model.shop.profit.report.ShopProfitReportVo;
import com.fowo.api.model.shop.profit.report.other.fee.ShopProfitReportOtherFeeItemVo;
import com.fowo.api.model.stock.in.StockInSearchParamPo;
import com.fowo.api.model.stock.in.StockInVo;
import com.fowo.api.model.stock.in.product.StockInProductItemVo;
import com.fowo.api.model.stock.out.StockOutSearchParamPo;
import com.fowo.api.model.stock.out.StockOutVo;
import com.fowo.api.model.stock.out.product.StockOutProductItemVo;
import com.fowo.api.model.supplier.SupplierVo;
import com.fowo.api.model.warehouse.WarehouseVo;
import com.fowo.api.model.warehouse.bin.WarehouseBinVo;
import com.fowo.api.model.warehouse.bin.products.WarehouseBinProductsItemVo;
import com.fowo.api.model.wms.order.WmsOrderVo;
import com.fowo.api.model.wms.order.item.WmsOrderItemItemVo;
import com.fowo.api.service.*;
import com.fowo.api.service.handleWork.jindieEntity.adjustmentOrder;
import com.fowo.api.service.handleWork.jindieEntity.supplier;
import com.fowo.api.syncLingxingApi.entity.TmpSyncLingxingToProduct;
import com.fowo.api.syncLingxingApi.service.impl.TmpSyncLingxingToProductServiceImpl;
import com.fowo.api.syncLingxingApi.service.syncImpl.SyncLxBatchProductInfoServiceImpl;
import com.fowo.api.syncLingxingApi.service.syncImpl.SyncProductListServiceImpl;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysRole;
import com.fowo.api.sys.entity.SysUser;
import com.fowo.api.sys.entity.SysUserRole;
import com.fowo.api.sys.mapper.SysRoleMapper;
import com.fowo.api.sys.mapper.SysUserMapper;
import com.fowo.api.sys.mapper.SysUserRoleMapper;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.user.model.JwtUserInfo;
import com.fowo.api.util.JdbcUtils;
import com.fowo.api.util.LocalDateUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author: <a href="1006319834@qq.com">王冰卿</a>
 * @Description:
 * @Version: 1.0
 * @Date: Created in 2023/3/19 23:53
 * @Modified By:
 */
@Service
@Slf4j
@DS("ds24")
public class LingXingInterfaceServiceImpl implements LingXingInterfaceService {
    @Resource
    private RestUtilLingXing restUtilLingXing;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private StockInService stockInService;
    @Resource
    private StockOutService stockOutService;
    //    @Resource
//    private OpeningInventoryService openingInventoryService;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private ShopProfitReportService shopProfitReportService;
    @Resource
    private LingXingInterfaceMapper lingXingInterfaceMapper;
    @Resource
    private SalesOutboundServiceImpl salesOutboundService;
    @Resource
    private SupplierServiceImpl supplierService;
    @Resource
    private FileService fileService;
    @Resource
    private ProductServiceImpl productService;
    @Resource
    private WarehouseServiceImpl warehouseService;
    @Resource
    private WarehouseMapper warehouseMapper;
    @Resource
    private WarehouseBinMapper warehouseBinMapper;
    @Resource
    private WarehouseBinServiceImpl warehouseBinService;
    @Resource
    private WarehouseBinProductsMapper warehouseBinProductsMapper;
    @Resource
    private AmazonOrderListMapper amazonOrderListMapper;
    @Resource
    private FBAInventoryServiceImpl fbaInventoryService;
    @Resource
    private FBAInvoiceService fbaInvoiceService;
    @Resource
    private FBAInvoiceMapper fbaInvoiceMapper;
    @Resource
    private ShopInfoMapper shopInfoMapper;
    @Resource
    private ListingFatherServiceImpl listingFatherServiceImpl;
    @Resource
    private WmsOrderService wmsOrderService;
    @Resource
    FbaShipmentServiceImpl fbaShipmentService;
    @Resource
    FbaShipmentProductServiceImpl fbaShipmentProductService;
    @Resource
    private RequisitionService requisitionService;
    @Resource
    private RequisitionMapper requisitionMapper;
    @Resource
    private ListingFatherMapper listingFatherMapper;
    @Resource
    private AdjustmentOrderServiceImpl adjustmentOrderService;
    @Resource
    private AdjustmentOrderMapper adjustmentOrderMapper;
    @Resource
    private InventoryListService inventoryListService;
    @Resource
    private InventoryListMapper inventoryListMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private WarehouseBinProductsServiceImpl warehouseBinProductsService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private WmsOrderMapper wmsOrderMapper;
    @Resource
    private InventoryBusinessService inventoryBusinessService;
    @Resource
    private ClassifyService classifyService;


    private static final String PRODUCT_LIST_URL = "https://openapi.lingxing.com/erp/sc/routing/data/local_inventory" +
            "/productList";
    private static final String PRODUCT_INFO_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/data/local_inventory/productInfo";

    private static final String PRODUCT_INFO_BATCH = "https://openapi.lingxing.com" +
            "/erp/sc/routing/data/local_inventory/batchGetProductInfo";
    private static final String STOCK_IN_LIST_URL = "https://openapi.lingxing" +
            ".com/erp/sc/routing/storage/inbound/getOrders";
    private static final String STOCK_OUT_LIST_URL = "https://openapi.lingxing" +
            ".com/erp/sc/routing/storage/outbound/getOrders";
    private static final String STOCK_LOCAL_URL = "https://openapi.lingxing.com" +
            "/inventory/center/openapi/storageReport/local/detail/page";
    private static final String STOCK_FBA_URL = "https://openapi.lingxing.com" +
            "/cost/center/openApi/fba/detail/query";
    private static final String SHOP_URL = "https://openapi.lingxing.com" +
            "/erp/sc/data/seller/lists";
    private static final String SHOP_PROFIT_REPORT_URL = "https://openapi.lingxing.com/bd/profit/report/open/report/seller/list";
    private static final String SALES_OUT_URL = "https://openapi.lingxing.com" +
            "/bd/sp/api/open/settlement/transaction/detail/list";
    private static final String WAREHOUSE_URL = "https://openapi.lingxing.com" +
            "/erp/sc/data/local_inventory/warehouse";
    private static final String WAREHOUSEBIN_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/data/local_inventory/warehouseBin";
    private static final String AMAZONORDERLIST_URL = "https://openapi.lingxing.com" +
            "/erp/sc/data/mws/orders";
    private static final String LISTING_URL = "https://openapi.lingxing.com:9990" +
            "/erp/sc/data/mws/listing";
    private static final String AMAZONORDERLISTDETAIL_URL = "https://openapi.lingxing.com" +
            "/erp/sc/data/mws/orderDetail";
    private static final String PURCHASEORDERLIST_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/data/local_inventory/purchaseOrderList";
    private static final String SUPPLIER = "https://openapi.lingxing.com" +
            "/erp/sc/data/local_inventory/supplier";
    private static final String OUTBOUNDORDER_URL = "https://openapi.lingxing.com" +
            "/order/amzod/api/fbaOutboundOrder/page";
    private static final String AFTERSALELIST_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/amzod/order/afterSaleList";
    private static final String logisticsInformation = "https://openapi.lingxing.com" +
            "/order/amzod/api/orderDetails/logisticsInformation";
    private static final String productInformation = "https://openapi.lingxing.com" +
            "/order/amzod/api/orderDetails/productInformation";
    private static final String returnInformation = "https://openapi.lingxing.com" +
            "/order/amzod/api/orderDetails/returnInformation";
    private static final String RoutingOrderList_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/order/Order/getOrderList";
    private static final String FBAInventory_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/fba/fbaStock/fbaList";
    private static final String SalesDailyList_URL = "https://openapi.lingxing.com" +
            "/erp/sc/data/sales_report/asinDailyLists";
    private static final String InventoryDetails_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/data/local_inventory/inventoryDetails";
    private static final String InventoryBinDetails_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/data/local_inventory/inventoryBinDetails";
    private static final String InboundShipmentList_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/storage/shipment/getInboundShipmentList";

    private static final String InboundShipmentListMwsDetailList_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/storage/shipment/getInboundShipmentListMwsDetailList";

    private static final String InboundShipmentSendGoods_URL = "https://openapi.lingxing.com" +
            "/erp/sc/storage/shipment/sendGoods";
    private static final String ShipmentList_URL = "https://openapi.lingxing.com" +
            "/erp/sc/data/fba_report/shipmentList";
    private static final String WmsOrderList_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/wms/order/wmsOrderList";
    private static final String StorageAllocationList_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/inventoryReceipt/StorageAllocation/getStorageAllocationList";
    private static final String AdjustmentOrderList_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/inventoryReceipt/StorageAdjustment/getStorageAdjustOrderList";
    private static final String InventoryList_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/inventoryReceipt/InventoryCheck/getOrderDetail";

    private static final String Customer_URL = "https://openapi.lingxing.com" +
            "/erp/sc/data/account/lists";
    private static final String CLASSIFY_URL = "https://openapi.lingxing.com/erp/sc/routing/data/local_inventory/category";

    private static final String STORAGEADJUSTORDER_URL = "https://openapi.lingxing.com" +
            "/erp/sc/routing/inventoryReceipt/StorageAdjustment/getStorageAdjustOrderList";

    private static final String TOKEN_URL = "https://openapi.lingxing.com:9990/api/auth-server/oauth/access-token";
    private static final String APPID = "ak_s4t9uVnYKwknd";
    private static final String APP_SECRET = "xZHRMyjrRAfJkvVCoVWcxQ==";
    private static final Map<String, Object> REQUEST_PARAMS = Map.of("appId", APPID, "appSecret", APP_SECRET);
    @Resource
    private ListingFatherServiceImpl ListingFatherService;

    /**
     * 获取token工具方法
     *
     * @return
     */
    private String getToken() {
        Object lingXingRequest = restUtilLingXing.lingXingRequest("1", RequestMethodKind.Post.getValue(), REQUEST_PARAMS,
                TOKEN_URL, null, null);
        JSONObject jsonObject = (JSONObject) lingXingRequest;
        if (!"200".equals(jsonObject.get("code"))) {
            Assert.isTrue(false, "获取AccessToken失败，错误信息：" + jsonObject.get("msg"));
        }
        //取得access-token
        return ((JSONObject) jsonObject.get("data")).get("access_token").toString();
    }

    /**
     * 循环获取领星数据直到成功
     *
     * @param result
     * @param requestBody
     * @param listingUrl
     * @return
     */
    private JSONObject regainLingXingData(JSONObject result, Map<String, Object> requestBody, String listingUrl) {
        int cnt = 0;
        while (result.getInteger("code") != 0) {
            ++cnt;
            if (cnt > 10) {
                log.info(">> request failed, after retry 10 times");
                return result;
            } else {
                log.info(">> try time " + cnt + "/10.");
            }

            Object inventoryListResultObj = new JSONObject();
            Integer code = result.getInteger("code");
//				ip不在白名单，appId不存在，appSecret不正确，请求的api未授权，请求的api未授权，接口签名不正确，
            if (code == 3001002 || code == 2001001 || code == 2001002 || code == 2001004 || code == 2001006 || code == 3001001) {
                Assert.isTrue(false, "查询订单列表失败，原因：" + result.getString("msg"));
                result = new JSONObject();
                break;
            }
            if (code == 3001008 || code == 2001005) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    log.error("请求失败" + code);
                }
            }
            String token = getToken();
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("access_token", token);
            requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
            requestParams.put("timestamp", System.currentTimeMillis() / 1000);
            inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    requestParams, listingUrl,
                    null, requestBody);
            JSONObject o = (JSONObject) inventoryListResultObj;
            if (o.getInteger("code") == 0) {
                result = new JSONObject();
                result = (JSONObject) inventoryListResultObj;
            } else {
                log.info(o.toString());
            }
        }
        return result;
    }

    /**
     * 同步产品
     */
    @Override
    public void syncProduct() {
        //获取token
        String token = getToken();
        //查询产品最后更新时间
//		long lastUpdateTimeStamp = (System.currentTimeMillis()/1000)-86400;
        //定义分页参数
        Integer offset = 0;
//		 offset = 0;
        Integer length = 1000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
//		requestBody.put("create_time_start", lastUpdateTimeStamp);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询产品列表
        Object productListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, PRODUCT_LIST_URL,
                null, requestBody);
        JSONObject productListResult = (JSONObject) productListResultObj;
        if (productListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(productListResult, requestBody, PRODUCT_LIST_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                productListResult = new JSONObject();
                productListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
            }
        }
//        if (!"0".equals(productListResult.get("code").toString())) {
//            Assert.isTrue(false, "查询商品列表失败，原因：" + productListResult.get("msg").toString());
//        }
        JSONArray result = productListResult.getJSONArray("data");
        //转换成product并入库
        try {
            handleProductResult(result);
        } catch (Exception e) {
            log.info("产品入库失败-------", e.getMessage());
        }

//		判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) productListResult.get("total");
        if ((total - offset) > length) {
            int pageNum = (total - offset) / length;
            if ((total - offset) % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", requestParams.get("timestamp"));
                int offset1 = (i * length) + offset;
                System.out.println("------------------------------offset----------------------------" + offset1);
                requestBody.put("offset", offset1);
                //查询产品列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, PRODUCT_LIST_URL,
                        null, requestBody);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (continueSearchResultJSON.getInteger("code") != 0) {
                    JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, requestBody, PRODUCT_LIST_URL);
                    if (jsonObject == null) {
                        return;
                    }
                    if (jsonObject.getInteger("code") == 0) {
                        continueSearchResultJSON = new JSONObject();
                        continueSearchResultJSON = jsonObject;
                    } else {
                        Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
                    }
                }
//				if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
//					Assert.isTrue(false, "查询商品列表失败，原因："+ continueSearchResultJSON.get("msg").toString());
//				}
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成product并入库
                try {
                    handleProductResult(continueSearchResult);
                } catch (Exception e) {
                    log.info("产品入库失败---------", e.getMessage());
                }
            }
        }
    }


    @Override
    public void syncByCreateTimeProduct() {
        //获取token
        String token = getToken();
        String timeString = "";
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONDAY, -2);
        Date time = calendar.getTime();
        long timestamp = time.getTime() / 1000;
        //查询产品最后更新时间
//		long lastUpdateTimeStamp = (System.currentTimeMillis()/1000)-86400;
        //定义分页参数
        Integer offset = 0;
//        Integer length = 1000;
        Integer length = 50;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("create_time_start", timestamp);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询产品列表
        Object productListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, PRODUCT_LIST_URL,
                null, requestBody);
        JSONObject productListResult = (JSONObject) productListResultObj;
        if (productListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(productListResult, requestBody, PRODUCT_LIST_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                productListResult = new JSONObject();
                productListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
            }
        }
//        if (!"0".equals(productListResult.get("code").toString())) {
//            Assert.isTrue(false, "查询商品列表失败，原因：" + productListResult.get("msg").toString());
//        }
        JSONArray result = productListResult.getJSONArray("data");
        //转换成product并入库
        try {
            handleProductResult(result);
        } catch (Exception e) {
            log.info("产品入库失败-------", e.getMessage());
        }

//		判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) productListResult.get("total");
        if ((total - offset) > length && 1 > 2) {
            int pageNum = (total - offset) / length;
            if ((total - offset) % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", requestParams.get("timestamp"));
                int offset1 = (i * length) + offset;
                System.out.println("------------------------------offset----------------------------" + offset1);
                requestBody.put("offset", offset1);
                //查询产品列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, PRODUCT_LIST_URL,
                        null, requestBody);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (continueSearchResultJSON.getInteger("code") != 0) {
                    JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, requestBody, PRODUCT_LIST_URL);
                    if (jsonObject == null) {
                        return;
                    }
                    if (jsonObject.getInteger("code") == 0) {
                        continueSearchResultJSON = new JSONObject();
                        continueSearchResultJSON = jsonObject;
                    } else {
                        Assert.isTrue(false, "查询列表失败，原因：code不为零查询失败");
                    }
                }
//				if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
//					Assert.isTrue(false, "查询商品列表失败，原因："+ continueSearchResultJSON.get("msg").toString());
//				}
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成product并入库
                try {
                    handleProductResult(continueSearchResult);
                } catch (Exception e) {
                    log.info("产品入库失败---------", e.getMessage());
                }
            }
        }
    }

    @Override
    public void syncByUpdateTimeProduct() {
//获取token
        String token = getToken();
        String timeString = "";
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONDAY, -2);
        Date time = calendar.getTime();
        long timestamp = time.getTime() / 1000;
        //查询产品最后更新时间
//		long lastUpdateTimeStamp = (System.currentTimeMillis()/1000)-86400;
        //定义分页参数
        Integer offset = 0;
//        Integer length = 1000;
        Integer length = 50;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("update_time_start", timestamp);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询产品列表
        Object productListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, PRODUCT_LIST_URL,
                null, requestBody);
        JSONObject productListResult = (JSONObject) productListResultObj;
        if (productListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(productListResult, requestBody, PRODUCT_LIST_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                productListResult = new JSONObject();
                productListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
            }
        }
//        if (!"0".equals(productListResult.get("code").toString())) {
//            Assert.isTrue(false, "查询商品列表失败，原因：" + productListResult.get("msg").toString());
//        }
        JSONArray result = productListResult.getJSONArray("data");
        //转换成product并入库
        try {
            handleProductResult(result);
        } catch (Exception e) {
            log.info("产品入库失败-------", e.getMessage());
        }

//		判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) productListResult.get("total");
        if ((total - offset) > length && 1 > 2) {
            int pageNum = (total - offset) / length;
            if ((total - offset) % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", requestParams.get("timestamp"));
                int offset1 = (i * length) + offset;
                System.out.println("------------------------------offset----------------------------" + offset1);
                requestBody.put("offset", offset1);
                //查询产品列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, PRODUCT_LIST_URL,
                        null, requestBody);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (continueSearchResultJSON.getInteger("code") != 0) {
                    JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, requestBody, PRODUCT_LIST_URL);
                    if (jsonObject == null) {
                        return;
                    }
                    if (jsonObject.getInteger("code") == 0) {
                        continueSearchResultJSON = new JSONObject();
                        continueSearchResultJSON = jsonObject;
                    } else {
                        Assert.isTrue(false, "查询列表失败，原因：code不为零查询失败");
                    }
                }
//				if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
//					Assert.isTrue(false, "查询商品列表失败，原因："+ continueSearchResultJSON.get("msg").toString());
//				}
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成product并入库
                try {
                    handleProductResult(continueSearchResult);
                } catch (Exception e) {
                    log.info("产品入库失败---------", e.getMessage());
                }
            }
        }
    }

    private void handleProductResult(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
//		result.forEach(t -> {
        for (Object t : result) {
            JSONObject product = (JSONObject) t;
            String picUrl = product.getString("pic_url");
            String sku = product.getString("sku");
            if (org.apache.commons.lang3.StringUtils.isNotBlank(sku)) {
                Product one = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, sku));
                if (null != one) {
                    Product products = new ProductVo();
                    BeanUtils.copyProperties(one, products);
                    products.setName(product.get("product_name").toString());
                    products.setSku(product.get("sku").toString());
                    products.setProcurementCost(product.getBigDecimal("cg_price"));
//                    products.setModel(product.getString("model"));
                    products.setLastUpdateTime(products.getCreateTime());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Long timeStamp = Long.valueOf(product.get("create_time").toString() + "000");
                    Long timeStampup = Long.valueOf(product.get("update_time").toString() + "000");
                    String create_time = sdf.format(timeStamp);
                    String updata_time = sdf.format(timeStampup);
                    try {
                        products.setCreateTime(sdf.parse(create_time));
//                        products.setLastUpdateTime(products.getCreateTime());
//                        products.setLastUpdateTime(sdf.parse(updata_time));
                        products.setLastUpdateTime(new Date());
                    } catch (ParseException e) {
                        Assert.isTrue(false, "日期转换失败");
                    }
//                    products.setPicUrl(updateUrl(sku, picUrl));
                    if (jwtUserInfo != null) {
                        products.setCreateUser(jwtUserInfo.getUserId());
                        products.setLastUpdateUser(jwtUserInfo.getUserId());
                    }
                    products.setClassify(product.getLong("cid"));
                    products.setProductType(product.getString("category_name"));
                    products.setBrand(product.getLong("bid"));
                    products.setTradeName(product.getString("brand_name"));
                    products.setPurchasingDeliveryTime(product.getInteger("cg_delivery"));
                    products.setTransportCost(product.getBigDecimal("cg_transport_costs"));
                    products.setRemarks(product.getString("purchase_remark"));
                    products.setLxProductId(Long.valueOf(product.get("id").toString()));
                    if (product.getInteger("status") == 0) {
                        products.setSalesStatus("CP04");
                    }
                    if (product.getInteger("status") == 1) {
                        products.setSalesStatus("CP02");
                    }
                    if (product.getInteger("status") == 2) {
                        products.setSalesStatus("CP01");
                    }
                    if (product.getInteger("status") == 3) {
                        products.setSalesStatus("CP03");
                    }
                    products.setType("CP01");
                    products.setIsCombo(product.getInteger("is_combo") == 0 ? false : true);
                    products.setDeveloper(product.getLong("product_developer_uid"));
                    products.setBuyer(product.getLong("cg_opt_uid"));
                    //图片处理
                    List<SysFile> fileList = new ArrayList<>();
                    if (product.get("pic_url") != null && org.apache.commons.lang3.StringUtils.isNotBlank(product.getString("pic_url"))) {
                        MultipartFile multipartFile = null;
                        try {
                            multipartFile = onlineAddressTransferFile(product.getString("pic_url"));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            fileList.add(fileService.upload(multipartFile, null));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        products.setPicUrl(fileList);
                    }
                    products.setSupplierQuote(JSON.toJSONString(product.get("supplier_quote")));
                    try {
//                        productService.update(products);
                        productMapper.updateById(products);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    Product products = new ProductVo();
                    products.setName(product.get("product_name").toString());
                    products.setSku(product.get("sku").toString());
                    products.setProcurementCost(product.getBigDecimal("cg_price"));
//                    products.setPicUrl(updateUrl(sku, picUrl));
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Long timeStamp = Long.valueOf(product.get("create_time").toString() + "000");
                    Long timeStampup = Long.valueOf(product.get("update_time").toString() + "000");
                    String create_time = sdf.format(timeStamp);
                    String updata_time = sdf.format(timeStampup);
                    try {
                        products.setCreateTime(sdf.parse(create_time));
//                        products.setLastUpdateTime(products.getCreateTime());
                        products.setLastUpdateTime(new Date());
                    } catch (ParseException e) {
                        Assert.isTrue(false, "日期转换失败");
                    }
                    if (jwtUserInfo != null) {
                        products.setCreateUser(jwtUserInfo.getUserId());
                        products.setLastUpdateUser(jwtUserInfo.getUserId());
                    }
                    products.setClassify(product.getLong("cid"));
                    products.setProductType(product.getString("category_name"));
                    products.setBrand(product.getLong("bid"));
                    products.setTradeName(product.getString("brand_name"));
                    products.setLxProductId(Long.valueOf(product.get("id").toString()));
                    //图片处理
                    List<SysFile> fileList = new ArrayList<>();
                    if (products.getPicUrl() == null || products.getPicUrl().size() < 1) {
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(product.getString("pic_url"))) {
                            MultipartFile multipartFile = null;
                            try {
                                multipartFile = onlineAddressTransferFile(product.getString("pic_url"));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                fileList.add(fileService.upload(multipartFile, null));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            products.setPicUrl(fileList);
                        }
                    }
                    products.setPurchasingDeliveryTime(product.getInteger("cg_delivery"));
                    products.setTransportCost(product.getBigDecimal("cg_transport_costs"));
                    products.setRemarks(product.getString("purchase_remark"));
                    if (product.getInteger("status") == 0) {
                        products.setSalesStatus("CP04");
                    }
                    if (product.getInteger("status") == 1) {
                        products.setSalesStatus("CP02");
                    }
                    if (product.getInteger("status") == 2) {
                        products.setSalesStatus("CP01");
                    }
                    if (product.getInteger("status") == 3) {
                        products.setSalesStatus("CP03");
                    }
                    products.setType("CP01");
                    products.setIsCombo(product.getInteger("is_combo") == 0 ? false : true);
                    products.setDeveloper(product.getLong("product_developer_uid"));
                    products.setBuyer(product.getLong("cg_opt_uid"));
                    products.setSupplierQuote(JSON.toJSONString(product.get("supplier_quote")));
                    productMapper.insert(products);
                }
            }
        }
    }

    /**
     * 同步并更新供应商
     *
     * @throws Exception
     */
    @Override
    public void syncSupplier() throws Exception {
        //获取token
        String token = getToken();
        Integer offset = 0;
        Integer length = 10000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询供应商列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, SUPPLIER,
                null, requestBody);

        supplier supplier = JSON.parseObject(String.valueOf(inventoryListResultObj), supplier.class);
        for (int i = 0; i < supplier.getData().size(); i++) {
            com.fowo.api.service.handleWork.jindieEntity.supplier.DataDTO dataDTO = supplier.getData().get(i);
            Supplier one = supplierService.getOne(Wrappers.<Supplier>query().lambda().eq(Supplier::getSupplierCode, dataDTO.getSupplierId()));
            if (one == null) {
                SupplierVo model = new SupplierVo();
                model.setSupplierName(dataDTO.getSupplierName());
                model.setSupplierFullName(dataDTO.getSupplierName());
                model.setSupplierCode(dataDTO.getSupplierId().toString());
                model.setDelFlag(dataDTO.getIsDelete() == 0 ? true : false);
                if (!"".equals(dataDTO.getPurchaser()) && !(dataDTO.getPurchaser() == null)) {
                    if (dataDTO.getPurchaser().contains(",")) {
                        String s = Arrays.asList(dataDTO.getPurchaser().split(",")).get(0);
                        model.setFollowUpPerson(Long.valueOf(s));
                    } else {
                        model.setFollowUpPerson(Long.valueOf(dataDTO.getPurchaser()));//跟进人
                    }
                }
                model.setScale(String.valueOf(dataDTO.getEmployees()));
                model.setContacts(dataDTO.getContactPerson());
                model.setContactsPhone(dataDTO.getContactNumber());
                model.setQqWx(dataDTO.getQq());
                model.setEmail(dataDTO.getEmail());
                model.setRemarks(dataDTO.getRemark());
                model.setSettleMethods(dataDTO.getSettlementMethodText());
                model.setPayType(dataDTO.getPaymentMethodText());
                model.setAccountName(dataDTO.getAccountName());
                model.setAccountBank(dataDTO.getOpenBank());
                model.setAccount(dataDTO.getBankCardNumber());
                supplierService.create(model);
            } else {
                SupplierVo supplierVo = new SupplierVo();
                supplierVo.setId(one.getId());
                supplierVo.setSupplierName(dataDTO.getSupplierName());
                supplierVo.setSupplierFullName(dataDTO.getSupplierName());
                supplierVo.setDelFlag(dataDTO.getIsDelete() == 0 ? true : false);
                if (!"".equals(dataDTO.getPurchaser()) && !(dataDTO.getPurchaser() == null)) {
                    if (dataDTO.getPurchaser().contains(",")) {
                        String s = Arrays.asList(dataDTO.getPurchaser().split(",")).get(0);
                        supplierVo.setFollowUpPerson(Long.valueOf(s));
                    } else {
                        supplierVo.setFollowUpPerson(Long.valueOf(dataDTO.getPurchaser()));//跟进人
                    }
                }
                supplierVo.setScale(String.valueOf(dataDTO.getEmployees()));
                supplierVo.setContacts(dataDTO.getContactPerson());
                supplierVo.setContactsPhone(dataDTO.getContactNumber());
                supplierVo.setQqWx(dataDTO.getQq());
                supplierVo.setEmail(dataDTO.getEmail());
                supplierVo.setRemarks(dataDTO.getRemark());
                supplierVo.setSettleMethods(dataDTO.getSettlementMethodText());
                supplierVo.setPayType(dataDTO.getPaymentMethodText());
                supplierVo.setAccountName(dataDTO.getAccountName());
                supplierVo.setAccountBank(dataDTO.getOpenBank());
                supplierVo.setAccount(dataDTO.getBankCardNumber());
                supplierService.update(supplierVo);
            }
        }
    }

    /**
     * 同步更新店铺
     */
    @Override
    public void syncShop() {
        //获取token
        String token = getToken();
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Get.getValue(),
                requestParams, SHOP_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0 && inventoryListResult.getBoolean("success")) {
            Assert.isTrue(false, "查询店铺列表失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONArray("data");
        //转换成并存库
        saveShop(result);
        log.info(">>>>>>>>>>同步店铺信息完成");
    }


    /**
     * 更新并拉取最新仓库
     */
    @Override
    public void syncWarehouse() {
        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer length = 1000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
//       仓库类型 1=本地仓【默认值】3=海外仓
//        requestBody.put("type", 3);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询仓库列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, WAREHOUSE_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询仓库列表失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONArray("data");
        //转换成并存库
        saveWarehouse(result);
        log.info("操作成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void syncFBAWarehouse() throws Exception {
        QueryWrapper<FBAInventory> FBAInventory = new QueryWrapper();
        FBAInventory.select("wname");
        FBAInventory.groupBy("wname");
        List<com.fowo.api.entity.FBAInventory> list = fbaInventoryService.list(FBAInventory);
        for (int i = 0; i < list.size(); i++) {
            com.fowo.api.entity.FBAInventory fbaInventory = list.get(i);
            Warehouse one = warehouseService.getOne(Wrappers.<Warehouse>query().lambda().eq(Warehouse::getName, fbaInventory.getWname()));
            if (one != null) {
                continue;
            }
            WarehouseVo vo = new WarehouseVo();
            vo.setName(fbaInventory.getWname());
            vo.setType("2");
            vo.setIsOwn("2");
            vo.setWidType("2");
            warehouseService.create(vo);
        }

    }

    /**
     * 保存店铺数据
     *
     * @param result
     */
    private void saveShop(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
        result.forEach(t -> {
            JSONObject object = (JSONObject) t;
//			Integer status = object.getInteger("status");
            ShopInfo info = shopInfoService.getOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getShopCode, object.getString("sid")));
            if (null != info) {
                info.setShopName(object.getString("name"));//店铺名
                info.setShopCode(object.getString("sid"));//店铺id领星ERP对企业已授权店铺的唯一标识
                info.setSellerId(object.getString("seller_id"));//亚马逊店铺id
                info.setCountry(object.getString("country"));
                info.setLastUpdateTime(new Date());
                try {
                    shopInfoService.updateById(info);
                } catch (Exception e) {
                    log.error("创建店铺失败", e);
                }
            } else {
                info = new ShopInfo();
                info.setCreateTime(new Date());
                info.setLastUpdateTime(new Date());
                info.setShopCode(object.getString("sid"));
                info.setSellerId(object.getString("seller_id"));
                info.setShopName(object.getString("name"));
                info.setCountry(object.getString("country"));
                shopInfoService.save(info);
            }
        });
    }


    /**
     * 更新新增仓库
     *
     * @param result
     */
    public void saveWarehouse(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
        for (Object t : result) {
            JSONObject o = (JSONObject) t;
            Warehouse wid = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getName, o.get("name")));
            WarehouseVo vo = new WarehouseVo();
            if (null != wid) {
                vo.setId(wid.getId());
                vo.setName(o.getString("name"));
                vo.setWidType(o.getString("type"));
                vo.setIsOwn(o.getString("type"));
                vo.setWid(o.getString("wid"));
                vo.setDelFlag(o.getString("is_delete").equals("1") ? true : false);
                try {
                    warehouseService.update(vo);
                    continue;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                vo.setName(o.getString("name"));
                vo.setDelFlag(o.getString("is_delete").equals("1") ? true : false);
                vo.setWid(o.getString("wid"));
                vo.setIsOwn(o.getString("type"));
                vo.setWidType(o.getString("type"));
                try {
                    warehouseService.create(vo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 更新并拉取最新仓位数据
     */
    @Override
    public void syncWarehouseBin(JSONObject wid) throws Exception {
        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer limit = 1000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        if (wid != null && wid.size() > 0) {
            requestBody.put("wid", wid.getString("wid"));
        }
        requestBody.put("limit", limit);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询仓位列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, WAREHOUSEBIN_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody, WAREHOUSEBIN_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
            }
        }

        saveWarehouseBin(inventoryListResult.getJSONArray("data"));

        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total") - offset - limit;
        System.out.println(total);
        if (total > limit) {
            int pageNum = total / limit;
            if (total % limit != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i <= pageNum; i++) {
                offset = offset + limit;
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("limit", limit);
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, WAREHOUSEBIN_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                    JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, requestBody1, WAREHOUSEBIN_URL);
                    if (jsonObject == null) {
                        return;
                    }
                    if (jsonObject.getInteger("code") == 0) {
                        continueSearchResultJSON = new JSONObject();
                        continueSearchResultJSON = jsonObject;
                    } else {
                        Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
                    }
                }
                //转换成并存库
                try {
                    saveWarehouseBin(continueSearchResultJSON.getJSONArray("data"));
                } catch (Exception e) {
                    throw new Exception(e.getMessage());
                }
            }
        }
    }


    /**
     * 根据仓库编码同步新增数据并更新仓位列表
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void syncByWidWarehouseBin(String wid) throws Exception {
        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer limit = 1000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("limit", limit);
        requestBody.put("wid", wid);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询仓位列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, WAREHOUSEBIN_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody, WAREHOUSEBIN_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
            }
        }

        //List<Object> collect = inventoryListResult.getJSONArray("data").stream().filter(fm -> ((JSONObject)fm).getString("storage_bin").equals("2-F-02")).collect(Collectors.toList());
        saveWarehouseBin(inventoryListResult.getJSONArray("data"));
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total") - offset - limit;
        System.out.println(total);
        if (total > limit) {
            int pageNum = total / limit;
            if (total % limit != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i <= pageNum; i++) {
                offset = offset + limit;
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("limit", limit);
                requestBody1.put("wid", wid);
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, WAREHOUSEBIN_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                    JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, requestBody1, WAREHOUSEBIN_URL);
                    if (jsonObject == null) {
                        return;
                    }
                    if (jsonObject.getInteger("code") == 0) {
                        continueSearchResultJSON = new JSONObject();
                        continueSearchResultJSON = jsonObject;
                    } else {
                        Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
                    }
                }
                //转换成并存库
                //collect.addAll(inventoryListResult.getJSONArray("data").stream().filter(fm -> ((JSONObject)fm).getString("storage_bin").equals("2-F-02")).collect(Collectors.toList()));
                saveWarehouseBin(inventoryListResult.getJSONArray("data"));

            }
        }
        //log.error(JSON.toJSONString(collect));
    }

    @Override
    public void syncWmsOrderList() {
        //获取token
        String token = getToken();
        JSONObject object = new JSONObject();
        int pageSize = 50;
        int page = 1;
        object.put("page", page);
        object.put("page_size", pageSize);
        object.put("status_arr", 3);
        object.put("time_type", "delivered_at");
        String format = LocalDateUtils.format(new Date(), LocalDateUtils.DATE_PATTERN);
//        Calendar cal=Calendar.getInstance();
//        cal.add(Calendar.DATE,-1);
//        Date d=cal.getTime();
//        SimpleDateFormat sp=new SimpleDateFormat("yyyy-MM-dd");
//        String ZUOTIAN=sp.format(d);//获取昨天日期
//        object.put("start_date",ZUOTIAN);
//        object.put("end_date",ZUOTIAN);
        object.put("start_date", format);
        object.put("end_date", format);
        object.put("delivered_at", "delivered_at");
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, WmsOrderList_URL,
                null, object);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
//        log.info(inventoryListResult.toJSONString());
//        return;

        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, object, WmsOrderList_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
            }
        }
        addWmsOrderList(inventoryListResult.getJSONArray("data"));
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total");
        for (int i = 1; i < total / 50 + 1; i++) {
            page = page + 1;
            JSONObject object1 = new JSONObject();
            object1.put("page", page);
            object1.put("page_size", pageSize);
            object1.put("status_arr", 3);
            object1.put("delivered_at", "delivered_at");
//            object1.put("start_date",start_date);
//            object1.put("end_date",end_date);
            //定义URL参数
            Map<String, Object> requestParams1 = new HashMap<>();
            requestParams1.put("access_token", token);
            requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
            requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
            Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    requestParams1, WmsOrderList_URL,
                    null, object1);
            JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
            if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, object1, WmsOrderList_URL);
                if (jsonObject == null) {
                    return;
                }
                if (jsonObject.getInteger("code") == 0) {
                    continueSearchResultJSON = new JSONObject();
                    continueSearchResultJSON = jsonObject;
                } else {
                    Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
                }
            }
            //转换成并存库
            addWmsOrderList(continueSearchResultJSON.getJSONArray("data"));
        }
    }


    /**
     * 更新新增仓位数据
     *
     * @param result
     */
    private void saveWarehouseBin(JSONArray result) throws Exception {
//        int f = 0;
//        StringBuilder stringBuilder = new StringBuilder();
        if (Objects.isNull(result)) {
            return;
        }
        for (Object t : result) {
            JSONObject o = (JSONObject) t;
            WarehouseBinVo wbvo = new WarehouseBinVo();
            String ware_house_name = o.getString("Ware_house_name");
            Warehouse one = warehouseService.getOne(Wrappers.<Warehouse>query().lambda().eq(Warehouse::getName, ware_house_name));
            WarehouseBin storage_bin = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                    .eq(WarehouseBin::getStorageBin, o.getString("storage_bin"))
                    .eq(WarehouseBin::getWarehouseId, one.getId())
            );
            wbvo.setWarehouseId(one.getId());
            wbvo.setParentWarehouse(one.getId());
            wbvo.setType(o.getString("type"));
            wbvo.setStatus(o.getString("status"));
            wbvo.setSysType("1");
            wbvo.setUseType("2");
            wbvo.setStorageBin(o.getString("storage_bin"));
            JSONArray skuFnsku = o.getJSONArray("sku_fnsku");
            wbvo.setUsedQuantity(skuFnsku.size());
            wbvo.setLastUpdateTime(new Date());
            JwtUserInfo currentUser = JwtUserInfo.fromHeader();
            if (currentUser != null) {
                wbvo.setLastUpdateUser(currentUser.getUserId());
            }
            List<WarehouseBinProductsItemVo> warehouseBinProducts = new ArrayList<>();
            for (Object s : skuFnsku) {
                JSONObject os = (JSONObject) s;
                WarehouseBinProductsItemVo warehouseBinProduct = new WarehouseBinProductsItemVo();
                ShopInfo info = null;
                if (os.getString("seller_name") != null && !os.getString("seller_name").equals("")) {
                    info = shopInfoMapper.selectOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getShopName, os.getString("seller_name")));
//                    org.springframework.util.Assert.notNull(info,os.getString("seller_name")+"店铺不存在");
                    if (ObjUtil.isNotEmpty(info)) {
                        warehouseBinProduct.setShopId(info.getId());
                        warehouseBinProduct.setShopName(info.getShopName());
                    }
                    if (os.getString("fnsku") != null && !os.getString("fnsku").equals("")) {
                        warehouseBinProduct.setFnskuName(os.getString("fnsku"));
                        List<ListingFather> list = ListingFatherService.list(Wrappers.<ListingFather>query().lambda()
                                .eq(ListingFather::getFnsku, os.getString("fnsku"))
                                .eq(ListingFather::getSku, os.getString("sku"))
                                .eq(ObjUtil.isNotEmpty(info), ListingFather::getShop, ObjUtil.isNotEmpty(info) ? info.getId() : null));
//                        org.springframework.util.Assert.isTrue(list.size()>0,os.getString("fnsku")+",fnsku不存在");
//                        org.springframework.util.Assert.isTrue(list.size()>0,"sku:"+os.getString("sku")+"    fnsku:"+os.getString("fnsku")+"     shop:"+os.getString("store_id")+"    listing中未查到此条件fnsku");
                        if (list.size() > 0) {
                            warehouseBinProduct.setFnsku(list.size() > 0 ? list.get(0).getId() : null);
                            warehouseBinProduct.setMsku(list.size() > 0 ? list.get(0).getMsku() : null);
                        }
                    }
                }
                Product product = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getLxProductId, os.getString("product_id")));
                // org.springframework.util.Assert.notNull(product, os.getString("sku") + os.getString("product_id")+",产品不存在");
                if (Objects.nonNull(product)) {
                    warehouseBinProduct.setProductId(product.getId());
                    warehouseBinProduct.setProductName(product.getName());
                }
                warehouseBinProduct.setLxProductId(Long.valueOf(os.getString("product_id")));
                warehouseBinProduct.setSku(os.getString("sku"));
                warehouseBinProduct.setCreateTime(new Date());
                warehouseBinProduct.setDelFlag(false);
                warehouseBinProduct.setLastUpdateTime(new Date());
                warehouseBinProduct.setLastUpdateUser(wbvo.getLastUpdateUser());
                warehouseBinProducts.add(warehouseBinProduct);
                wbvo.setProducts(warehouseBinProducts);
            }
            if (storage_bin != null) {
                try {
                    wbvo.setId(storage_bin.getId());
//                    LambdaUpdateWrapper<WarehouseBinProducts>wrapper=new LambdaUpdateWrapper<>();
//                    wrapper.eq(WarehouseBinProducts::getParentId,wbvo.getId());
//                    wrapper.set(WarehouseBinProducts::getDelFlag,1);
//                    warehouseBinProductsService.update(wrapper);
                    SpringUtil.getBean(JdbcTemplate.class).update("delete from warehouse_bin_products where parent_id = ?", wbvo.getId());
                    warehouseBinService.update(wbvo);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new Exception("仓位:" + wbvo.getStorageBin() + "仓库id:" + wbvo.getWarehouseId() + "更新失败");
                }
            } else {
                try {
                    warehouseBinService.create(wbvo);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new Exception("仓位:" + wbvo.getStorageBin() + "仓库id:" + wbvo.getWarehouseId() + "新增失败");
                }
            }
        }
    }

    /**
     * 保存销售出库单数据
     */
    private void addWmsOrderList(JSONArray result) {
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
//        int f = 0;
//        StringBuilder stringBuilder = new StringBuilder();
        if (Objects.isNull(result)) {
            return;
        }
        for (Object t : result) {
            JSONObject o = (JSONObject) t;
            WmsOrderVo vo = new WmsOrderVo();
            WmsOrder wo_number = wmsOrderMapper.selectOne(Wrappers.lambdaQuery(WmsOrder.class).eq(WmsOrder::getWoNumber, o.getString("wo_number")));
            if (wo_number != null) {
                continue;
            }
            vo.setWoNumber(o.getString("wo_number"));//销售出库单号
            vo.setOrderNumber(o.getString("order_number"));//系统单号
            vo.setStatus(o.getString("status"));//单据状态
            if (o.getJSONArray("platform_order_no").size() != 0) {
                vo.setPlatformOrderNo((String) o.getJSONArray("platform_order_no").get(0));//平台单号
            }
            vo.setLogisticsProviderId(o.getString("logistics_provider_id"));//物流服务商
            vo.setLogisticsTypeId(o.getString("logistics_type_id"));//物流方式
//            if(o.getJSONArray("tag_names").size()!=0){
//                vo.setTagNames((String) o.getJSONArray("tag_names").get(0));//标签
//            }
            vo.setTagNames(o.getString("tag_names"));//标签
//            if(o.getString("seller_name")!=null&&!o.getString("seller_name").equals("")){
//                ShopInfo info = shopInfoMapper.selectOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getShopName, o.getString("seller_name")));
//                org.springframework.util.Assert.notNull(info,o.getString("seller_name")+"店铺不存在");
//                vo.setSid(info.getId());
//            }
            vo.setSellerName(o.getString("seller_name"));
            vo.setSid(o.getLong("sid"));//店铺
            vo.setSiteText(o.getString("site_text"));//站点名称
            vo.setPlatformName(o.getString("platform_name"));//平台名称
            vo.setDeliveredAt(o.getDate("delivered_at"));//出库时间
            vo.setDeliverer(o.getString("deliverer"));//发货人
            vo.setTargetCountry(o.getString("target_country"));//收货国家
//            System.out.println("收件人税号"+o.getString("recipient_tax_no"));
            vo.setRecipientTaxNo(o.getString("recipient_tax_no"));//收件人税号
            vo.setWaybillNo(o.getString("waybill_no"));//单运号
            vo.setTrackingNo(o.getString("tracking_no"));//跟踪号
//            Warehouse wid = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getWid, o.getString("wid")));
//            if(wid!=null){
//                vo.setWid(wid.getId());//仓库
//            }else {
//                Assert.isTrue(false, "该仓库："+o.getString("warehouse_name")+"编码："+o.getString("wid")+"不存在，请手动同步领星仓库数据");
//            }
//            log.info(o.getString("wid"));
            Warehouse warehouse_name = warehouseService.getOne(Wrappers.<Warehouse>query().lambda()
                    .eq(Warehouse::getDelFlag, 0)
                    .eq(Warehouse::getWid, o.getString("wid")).last("limit 1"));
//            org.springframework.util.Assert.notNull(warehouse_name, o.getString("warehouse_name") + ",仓库不存在");
            if (warehouse_name == null) {
                log.error("仓库不存在：" + o.getString("warehouse_name"));
                continue;
            }


            vo.setWName(warehouse_name.getName());
            vo.setWid(warehouse_name.getId());//仓库
            vo.setLogisticsEstimatedFreight(o.getBigDecimal("logistics_estimated_freight"));//预付运费
            vo.setLogisticsFreight(o.getBigDecimal("logistics_freight"));//物流运费
            vo.setStockDeliveredAt(o.getDate("stock_delivered_at"));//库存流水出库时间
            vo.setIsCheck(o.getString("is_check"));//是否验货
            vo.setIsWeigh(o.getString("is_weigh"));//是否称重
            vo.setIsSurfacePrint(o.getString("is_surface_print"));//面单是否打印
            vo.setIsorderPrint(o.getString("is_order_print"));//订单是否打印
            vo.setPkgLength(o.getBigDecimal("pkg_length"));//包裹尺寸长
            vo.setPkgHeight(o.getBigDecimal("pkg_height"));//包裹尺寸高
            vo.setPkgRealWeight(o.getBigDecimal("pkg_real_weight"));//包裹实重
            vo.setPkgWeight(o.getBigDecimal("pkg_weight"));//估算重量
            vo.setOrderType(o.getString("order_type"));//订单类型
            vo.setRecipient(o.getString("consignee"));//收件人
            vo.setPhone(o.getString("consignee_phone"));//收件人电话
            vo.setZipCode(o.getString("consignee_postcode"));//收件人邮编
            vo.setAddress(o.getString("consignee_full_address"));//收件地址
            vo.setOrderOriginAmount(o.getString("order_origin_amount"));//订单金额
            vo.setDeliverDeadline(o.getString("deliver_deadline"));//发货时限
            vo.setOrderCustomerServiceNotes(o.getString("order_customer_service_notes"));//客服备注
            vo.setOrderBuyerNotes(o.getString("order_buyer_notes"));//买家留言
            vo.setPkgVolume(o.getBigDecimal("pkg_volume"));//包裹体积
            vo.setProcessSn(o.getString("process_sn"));//加工单号
            vo.setOrderFrom(o.getString("order_from"));//订单来源
            vo.setBatchNo(o.getString("batch_no"));//批次号
            vo.setPicker(o.getString("picker"));//拣货人
            vo.setLogisticsStatus(o.getString("logistics_status"));//物流下单状态
            vo.setLogisticsMessage(o.getString("logistics_message"));//物流下单消息
            vo.setOrderCurrencyCode(o.getString("order_currency_code"));//订单币种
            vo.setSellerName(o.getString("seller_name"));//店铺名称
//            SysFile sysFile = new SysFile();
//            sysFile.setExt((String) o.getJSONObject("surface_file").get("ext"));
//            sysFile.setMimeType(o.getString("surface_file_type"));
//            sysFile.setFileSize((Long) o.getJSONObject("surface_file").get("size"));
            System.out.println("面单文件" + o.getJSONObject("surface_file"));
            vo.setLogisticsProviderName(o.getString("logistics_provider_name"));//物流服务商名称
            vo.setLogisticsTypeName(o.getString("logistics_type_name"));//物流方式名称
            vo.setPkgWeight(o.getBigDecimal("pkg_width"));//包裹尺寸宽
            vo.setPkgFeeWeight(o.getBigDecimal("pkg_fee_weight"));//包裹计费重
            vo.setPkgWeightUnit(o.getString("pkg_weight_unit"));//预估重量单位
//            System.out.println("预估重量单位"+o.getString("pkg_weight_unit"));
            vo.setPkgRealWeightUnit(o.getString("pkg_real_weight_unit"));//包裹实重单位
//            System.out.println("包裹实重单位"+o.getString("pkg_real_weight_unit"));
            vo.setPkgFeeWeightUnit(o.getString("pkg_fee_weight_unit"));//包裹计费重单位
//                        System.out.println("包裹计费重单位"+o.getString("pkg_real_weight_unit"));
            vo.setPkgSizeUnit(o.getString("pkg_size_unit"));//包裹尺寸单位
//            System.out.println("包裹尺寸单位"+o.getString("pkg_size_unit"));
            vo.setLogisticsEstimatedFreightCurrencyCode(o.getString("logistics_estimated_freight_currency_code"));//预估运费币种
//            System.out.println("预估运费币种"+o.getString("logistics_estimated_freight_currency_code"));
            vo.setLogisticsFreightCurrencyCode(o.getString("logistics_freight_currency_code"));//物流运费币种
//            System.out.println("物流运费币种"+o.getString("logistics_freight_currency_code"));
            vo.setSenderTaxNo(o.getString("sender_tax_no"));//发件人税号
//            System.out.println("发件人税号"+o.getString("sender_tax_no"));
            JSONArray product_info = o.getJSONArray("product_info");
            List<WmsOrderItemItemVo> wmsOrderItemItemVos = new ArrayList<>();
            for (Object p : product_info) {
                JSONObject proInfo = (JSONObject) p;
                WmsOrderItemItemVo wmsOrderItemItemVo = new WmsOrderItemItemVo();
                wmsOrderItemItemVo.setWodId(proInfo.getString("wod_id"));//出库单明细id
                wmsOrderItemItemVo.setSku(proInfo.getString("sku"));
                wmsOrderItemItemVo.setCreateTime(LocalDateUtils.toDate(LocalDateUtils.getTodayNow(), LocalDateUtils.DATE_TIME_PATTERN));
                Product product = productService.getProductBySku(proInfo.getString("sku")); // productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, proInfo.getString("sku")));
                org.springframework.util.Assert.notNull(product, proInfo.getString("sku") + "sku不存在");
                wmsOrderItemItemVo.setProductId(product.getId());
                wmsOrderItemItemVo.setProductIdName(product.getName());

                wmsOrderItemItemVo.setImg(product.getPicUrl());

                wmsOrderItemItemVo.setUnitPrice(proInfo.getBigDecimal("unit_price"));//商品单价
                wmsOrderItemItemVo.setCount(proInfo.getInteger("count"));//数量
                wmsOrderItemItemVo.setCustomization(proInfo.getString("customization"));//商品备注
                wmsOrderItemItemVo.setStockCost(proInfo.getBigDecimal("stock_cost"));//库存成本 (总计)
                wmsOrderItemItemVo.setBundleType(proInfo.getString("bundle_type"));//捆绑类型
                wmsOrderItemItemVo.setBundleWodId(proInfo.getString("bundle_wod_id"));//捆绑产品wod_id【只有拆分子产品才有】
                wmsOrderItemItemVo.setSellerSku(proInfo.getString("seller_sku"));//msku
                wmsOrderItemItemVo.setCnName(proInfo.getString("cn_name"));//中文申报名
                wmsOrderItemItemVo.setEnName(proInfo.getString("en_name"));//英文申报名
                wmsOrderItemItemVo.setThirdProductName(proInfo.getString("third_product_name"));//三方仓品名
                wmsOrderItemItemVo.setThirdProductCode(proInfo.getString("third_product_code"));//三方仓SKU
                wmsOrderItemItemVo.setCurrencyCode(proInfo.getString("currency_code"));//币种
                wmsOrderItemItemVo.setApportionFreight(proInfo.getBigDecimal("apportion_freight"));//分摊运费 (总计)
                wmsOrderItemItemVo.setApportionFreightSingle(proInfo.getBigDecimal("apportion_freight_single"));//分摊运费 (单个)
                wmsOrderItemItemVo.setLogisticsFreightCurrencyCode(proInfo.getString("logistics_freight_currency_code"));//物流运费币种
//                System.out.println("物流运费币种"+o.getString("logistics_freight_currency_code"));
                wmsOrderItemItemVos.add(wmsOrderItemItemVo);
            }
            vo.setProductInfo(wmsOrderItemItemVos);
//            if(f==1){
//                //调用领星根据批量sku批量查询产品详情，更新入产品表，再次同步
//
//                Assert.isTrue(false, "产品sku缺失："+stringBuilder+"已同步sku,请重新点击更新");
//            }
            try {
                Long userid = 0L;
                if (jwtUserInfo != null && jwtUserInfo.getUserId() != null) userid = jwtUserInfo.getUserId();
                if (vo.getCreateUser() == null) vo.setCreateUser(userid);
                if (vo.getLastUpdateUser() == null) vo.setLastUpdateUser(userid);
                wmsOrderService.create(vo);
                log.info("create order success. " + vo.getWoNumber());
                log.info("stock out ok.");
            } catch (Exception e) {
//                e.printStackTrace();
                log.error("create order failed." + vo.getWoNumber() + e.getMessage());
            }
            Object savePoint = null;
            try {
                savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
                wmsOrderService.stockOut(vo.getId());
            } catch (Exception e) {
                log.error("stock out failed." + vo.getWoNumber() + e.getMessage());
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            }
        }
    }

    /**
     * 销售出库单(已发货)同步领星新增数据
     * 时间类型：
     * 出库时间【单据操作】 delivered_at
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void syncAddWmsOrderList(JSONObject jsObject) {
        //获取token
        String token = getToken();
        JSONObject object = new JSONObject();
        int pageSize = 50;
        int page = 1;
        object.put("page", page);
        object.put("page_size", pageSize);
        object.put("status_arr", 3);
//        Calendar cal=Calendar.getInstance();
//        cal.add(Calendar.DATE,-1);
//        Date d=cal.getTime();String start_date,String end_date,
//        SimpleDateFormat sp=new SimpleDateFormat("yyyy-MM-dd");
//        String ZUOTIAN=sp.format(d);//获取昨天日期
//        object.put("start_date",ZUOTIAN);
//        object.put("end_date",ZUOTIAN);
        object.put("start_date", jsObject.getString("start_date"));
        object.put("end_date", jsObject.getString("end_date"));
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, WmsOrderList_URL,
                null, object);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, object, WmsOrderList_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
            }
        }
        addWmsOrderList(inventoryListResult.getJSONArray("data"));
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total");
        for (int i = 1; i < total / 50 + 1; i++) {
            page = page + 1;
            JSONObject object1 = new JSONObject();
            object1.put("page", page);
            object1.put("page_size", pageSize);
            object1.put("status_arr", 3);
            object1.put("start_date", jsObject.getString("start_date"));
            object1.put("end_date", jsObject.getString("end_date"));
            //定义URL参数
            Map<String, Object> requestParams1 = new HashMap<>();
            requestParams1.put("access_token", token);
            requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
            requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
            Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    requestParams1, WmsOrderList_URL,
                    null, object1);
            JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
            if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, object1, WmsOrderList_URL);
                if (jsonObject == null) {
                    return;
                }
                if (jsonObject.getInteger("code") == 0) {
                    continueSearchResultJSON = new JSONObject();
                    continueSearchResultJSON = jsonObject;
                } else {
                    Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
                }
            }
            //转换成并存库
            addWmsOrderList(continueSearchResultJSON.getJSONArray("data"));
        }
    }

    @Override
    public void syncAmazonOrderListStockOutWithErr() {
        List<String> ids = lingXingInterfaceMapper.getWmsOrderIdWithErr();
        for (String id : ids) {
            try {
                wmsOrderService.stockOut(Long.parseLong(id));
            } catch (Exception e) {
                log.error("出库失败（" + id + "）：" + e.getMessage());
            }
        }
    }


    /**
     * 同步新增亚马逊订单数据（当前日期前三天数据）时间类型默认为1下单日期
     */
    @Override
    public void syncAmazonOrderList() {
        String token = getToken();
        //定义分页参数
        Integer length = 10000;
        Integer offset = 0;
        // 获取当前日期
        Date today = new Date();
        // 往前推一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);
        calendar.add(Calendar.DATE, -3);
        Date yesterday = calendar.getTime();
        // 将日期格式化成字符串
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String yesterdayStr = dateFormat.format(yesterday);
        String today1 = dateFormat.format(today);
        String startDate = yesterdayStr;
        String endDate = today1;
        System.out.println(startDate + "qqq" + endDate);
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("start_date", startDate);
        requestBody.put("end_date", endDate);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, AMAZONORDERLIST_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody, AMAZONORDERLIST_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询订单列表失败，原因：code不为零查询失败");
            }
        }
        JSONArray result = inventoryListResult.getJSONArray("data");
        saveAmazonOrderList(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) inventoryListResult.get("total");
        System.out.println(total);
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("start_date", startDate);
                requestBody1.put("end_date", endDate);
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, AMAZONORDERLIST_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (continueSearchResultJSON.getInteger("code") != 0) {
                    JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, requestBody1, AMAZONORDERLIST_URL);
                    if (jsonObject == null) {
                        return;
                    }
                    if (jsonObject.getInteger("code") == 0) {
                        continueSearchResultJSON = new JSONObject();
                        continueSearchResultJSON = jsonObject;
                    } else {
                        Assert.isTrue(false, "查询订单列表失败，原因：code不为零查询失败");
                    }
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成并存库
                saveAmazonOrderList(continueSearchResult);
            }
        }
    }

    /**
     * 同步新增亚马逊订单数据（手动输入开始日期和结束日期）时间类型默认为1下单日期
     */
    @Override
    public void syncAmazonOrderList1(JSONObject object) {
        JSONArray results = new JSONArray();
        JSONObject totalObj = null;
        Integer length = 10000;
        JSONArray array = object.getJSONArray("startDate");
        String startDate = array.get(0).toString();
        String endDate = array.get(1).toString();
        for (int i = 0; i < 5; i++) {
            String token = getToken();
            //定义分页参数
            Integer offset = length * i;
            //定义查询参数
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("offset", offset);
            requestBody.put("length", length);
            requestBody.put("start_date", startDate);
            requestBody.put("end_date", endDate);
            //定义URL参数
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("access_token", token);
            requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
            requestParams.put("timestamp", System.currentTimeMillis() / 1000);
            //查询列表
            Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    requestParams, AMAZONORDERLIST_URL,
                    null, requestBody);
            JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
            if (inventoryListResult.getInteger("code") != 0) {
                JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody, AMAZONORDERLIST_URL);
                if (jsonObject == null) {
                    return;
                }
                if (jsonObject.getInteger("code") == 0) {
                    inventoryListResult = new JSONObject();
                    inventoryListResult = jsonObject;
                    totalObj = inventoryListResult;
                } else {
                    Assert.isTrue(false, "查询订单列表失败，原因：code不为零查询失败");
                }
            }
            totalObj = inventoryListResult;
            JSONArray result = null;
            result = inventoryListResult.getJSONArray("data");
            for (int j = 0; j < result.size(); j++) {
                JSONObject object1 = result.getJSONObject(j);
                results.add(object1);
            }
        }
        saveAmazonOrderList(results);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) totalObj.get("total") - (length * 5);
        System.out.println(total);
        Integer offset = 50000;
        if (total > length * 5) {
            int pageNum = total / (length * 5);
            if (total % (length * 5) != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 0; i < pageNum; i++) {
                JSONArray results1 = new JSONArray();
                for (int j = 0; j < 5; j++) {
                    String token = getToken();
                    //定义分页参数
                    offset = offset + 10000 * j;
                    //定义查询参数
                    Map<String, Object> requestBody1 = new HashMap<>();
                    requestBody1.put("offset", offset);
                    requestBody1.put("length", length);
                    requestBody1.put("start_date", startDate);
                    requestBody1.put("end_date", endDate);
                    //定义URL参数
                    Map<String, Object> requestParams1 = new HashMap<>();
                    requestParams1.put("access_token", token);
                    requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                    requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                    //查询列表
                    Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                            requestParams1, AMAZONORDERLIST_URL,
                            null, requestBody1);
                    JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
                    if (inventoryListResult.getInteger("code") != 0) {
                        JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody1, AMAZONORDERLIST_URL);
                        if (jsonObject == null) {
                            return;
                        }
                        if (jsonObject.getInteger("code") == 0) {
                            inventoryListResult = new JSONObject();
                            inventoryListResult = jsonObject;
                            totalObj = inventoryListResult;
                        } else {
                            Assert.isTrue(false, "查询订单列表失败，原因：code不为零查询失败");
                        }
                    }
                    JSONArray result = null;
                    result = inventoryListResult.getJSONArray("data");
                    for (int k = 0; k < result.size(); k++) {
                        JSONObject object1 = result.getJSONObject(k);
                        results1.add(object1);
                    }
                }
                saveAmazonOrderList(results1);
            }
        }
    }


    /**
     * 拉取最新数据新增到亚马逊订单数据
     */
    private void saveAmazonOrderList(JSONArray result) {
//        Connection conn = JdbcUtils.getConnnection();
        PreparedStatement ps = null;
        PreparedStatement psProduct = null;
//        PreparedStatement psid = null;
//        PreparedStatement ppid = null;
        PreparedStatement pd = null;
        try {
            String sql = "insert into amazon_order_list(id,create_time,last_update_time,shop_code,amazon_order_id,seller_name,order_status,order_total_amount,fulfillment_channel,postal_code,phone,buyer_email,is_return," +
                    "                             is_mcf_order,order_total_currency_code,sales_channel,tracking_number,refund_amount,purchase_date_local,purchase_date_local_utc," +
                    "                             shipment_date_local,last_update_date,last_update_date_utc,posted_date,posted_date_utc,purchase_date,purchase_date_utc,earliest_ship_date_utc," +
                    "                             gmt_modified,gmt_modified_utc,shipment_date,earliest_ship_date)" +
                    "                      values(?,?,?,?,?,?,?,?,?,?,?,?,?," +
                    "                             ?,?,?,?,?,?,?," +
                    "                             ?,?,?,?,?,?,?,?," +
                    "                             ?,?,?,?)";
            String sqlP = "insert into amazon_order_list_product(id,parent_amazon_order_list,asin,quantity_ordered,msku,sku,product_name,create_time,last_update_time)" +
                    "                            values(?,?,?,?,?,?,?,?,?)";
//            String sqlShopId = "SELECT id FROM shop_info WHERE shop_code=? and del_flag=0";
//            String sqlProductId = "SELECT id FROM product WHERE sku=? and del_flag=0";
            String sqlPd = "SELECT 1 FROM amazon_order_list WHERE amazon_order_id=? and shop_code=? and del_flag=0";
//            conn.setAutoCommit(false);
//            ps = conn.prepareStatement(sql);
//            psProduct = conn.prepareStatement(sqlP);
//            psid = conn.prepareStatement(sqlShopId);
//            ppid = conn.prepareStatement(sqlProductId);
//            pd = conn.prepareStatement(sqlPd);
            if (Objects.isNull(result)) {
                return;
            }
            List<AmazonOrderList> orderList = new ArrayList<>();
            List<AmazonOrderListProduct> productList = new ArrayList<>();
            for (Object t : result) {
                JSONObject jsonObject = (JSONObject) t;
//                psid.setString(1, jsonObject.getString("sid"));
//                ResultSet resultSet = psid.executeQuery();
//                Long sid = null;
//                while (resultSet.next()) {
//                    sid = resultSet.getLong("id");
//                }
//                if (sid == null) {
//                    ps.setNull(33, Types.NULL);
//                } else {
//                    ps.setLong(33, sid);
//                }
//                pd.setString(1, jsonObject.getString("amazon_order_id"));
//                pd.setString(2, jsonObject.getString("sid"));
//                if (sid == null) {
//                    pd.setNull(2, Types.NULL);
//                } else {
//                    pd.setLong(2, sid);
//                }
//                ResultSet resultSetpd = pd.executeQuery();
                Integer i = lingXingInterfaceMapper.selectCount(jsonObject.getString("amazon_order_id"), jsonObject.getString("sid"));
//                int one = 0;
//                while (resultSetpd.next()) {
//                    one = resultSetpd.getInt("1");
//                }
                if (i != null && i == 1) {
                    continue;
                }
                AmazonOrderList amazonOrderList = new AmazonOrderList();
                Long ID = IdWorker.getId(amazonOrderList);
                //批量添加测试
                amazonOrderList.setId(ID);
                amazonOrderList.setCreateTime(new Date());
                amazonOrderList.setLastUpdateTime(new Date());
                amazonOrderList.setShopCode(jsonObject.getString("sid"));
                Object o = redisTemplate.opsForValue().get("shop" + "_" + amazonOrderList.getShopCode());
                if (o != null) {
                    amazonOrderList.setShopId(Long.parseLong(o.toString()));
                } else {
                    QueryWrapper<ShopInfo> queryWrapper = new QueryWrapper();
                    queryWrapper.eq("shop_code", amazonOrderList.getShopCode());
                    ShopInfo shopInfo = shopInfoMapper.selectOne(queryWrapper);
                    if (shopInfo != null) {
                        amazonOrderList.setShopId(shopInfo.getId());
                        redisTemplate.opsForValue().set("shop" + "_" + amazonOrderList.getShopCode(), shopInfo.getId());
                    }
                }
                amazonOrderList.setAmazonOrderId(jsonObject.getString("amazon_order_id"));
                amazonOrderList.setSellerName(jsonObject.getString("seller_name"));
                amazonOrderList.setOrderStatus(jsonObject.getString("order_status"));
                amazonOrderList.setOrderTotalAmount(jsonObject.getString("order_total_amount"));
                amazonOrderList.setFulfillmentChannel(jsonObject.getString("fulfillment_channel"));
                amazonOrderList.setPostalCode(jsonObject.getString("postal_code"));
                amazonOrderList.setPhone(jsonObject.getString("phone"));
                amazonOrderList.setBuyerEmail(jsonObject.getString("buyer_email"));
                amazonOrderList.setIsReturn(jsonObject.getString("is_return"));
                amazonOrderList.setIsMcfOrder(jsonObject.getString("is_mcf_order"));
                amazonOrderList.setOrderTotalCurrencyCode(jsonObject.getString("order_total_currency_code"));
                amazonOrderList.setSalesChannel(jsonObject.getString("sales_channel"));
                amazonOrderList.setTrackingNumber(jsonObject.getString("tracking_number"));
                amazonOrderList.setRefundAmount(jsonObject.getString("refund_amount"));
                amazonOrderList.setPurchaseDateLocal(jsonObject.getString("purchase_date_local"));
                amazonOrderList.setPurchaseDateLocalUtc(jsonObject.getString("purchase_date_local_utc"));
                amazonOrderList.setPostedDate(jsonObject.getString("posted_date"));
                amazonOrderList.setPostedDateUtc(jsonObject.getString("posted_date_utc"));
                amazonOrderList.setPurchaseDate(jsonObject.getString("purchase_date"));
                amazonOrderList.setPurchaseDateUtc(jsonObject.getString("purchase_date_utc"));
                amazonOrderList.setEarliestShipDate(jsonObject.getString("earliest_ship_date"));
                amazonOrderList.setEarliestShipDateUtc(jsonObject.getString("earliest_ship_date_utc"));
                amazonOrderList.setGmtModified(jsonObject.getString("gmt_modified"));
                amazonOrderList.setGmtModifiedUtc(jsonObject.getString("gmt_modified_utc"));
                amazonOrderList.setShipmentDate(jsonObject.getString("shipment_date"));
                orderList.add(amazonOrderList);

//                ps.setLong(1, ID);
//                ps.setString(2, LocalDateUtils.getTodayNow());
//                ps.setString(3, LocalDateUtils.getTodayNow());
//                ps.setString(4, jsonObject.getString("sid"));
//                ps.setString(5, jsonObject.getString("amazon_order_id"));
//                ps.setString(6, jsonObject.getString("seller_name"));
//                ps.setString(7, jsonObject.getString("order_status"));
//                ps.setString(8, jsonObject.getString("order_total_amount"));
//                ps.setString(9, jsonObject.getString("fulfillment_channel"));
//                ps.setString(10, jsonObject.getString("postal_code"));
//                ps.setString(11, jsonObject.getString("phone"));
//                ps.setString(12, jsonObject.getString("buyer_email"));
//                ps.setString(13, jsonObject.getString("is_return"));
//                ps.setString(14, jsonObject.getString("is_mcf_order"));
//                ps.setString(15, jsonObject.getString("order_total_currency_code"));
//                ps.setString(16, jsonObject.getString("sales_channel"));
//                ps.setString(17, jsonObject.getString("tracking_number"));
//                ps.setString(18, jsonObject.getString("refund_amount"));
//                ps.setString(19, jsonObject.getString("purchase_date_local"));
//                ps.setString(20, jsonObject.getString("purchase_date_local_utc"));
//                ps.setString(21, jsonObject.getString("shipment_date_local"));
//                ps.setString(22, jsonObject.getString("last_update_date"));
//                ps.setString(23, jsonObject.getString("last_update_date_utc"));
//                ps.setString(24, jsonObject.getString("posted_date"));
//                ps.setString(25, jsonObject.getString("posted_date_utc"));
//                ps.setString(26, jsonObject.getString("purchase_date"));
//                ps.setString(27, jsonObject.getString("purchase_date_utc"));
//                ps.setString(28, jsonObject.getString("earliest_ship_date_utc"));
//                ps.setString(29, jsonObject.getString("gmt_modified"));
//                ps.setString(30, jsonObject.getString("gmt_modified_utc"));
//                ps.setString(31, jsonObject.getString("shipment_date"));
//                ps.setString(32, jsonObject.getString("earliest_ship_date"));
//                ps.addBatch();
                JSONArray amazonOrderProducts = jsonObject.getJSONArray("item_list");
                if (Objects.nonNull(amazonOrderProducts)) {
                    for (Object s : amazonOrderProducts) {
                        JSONObject jsonObject1 = (JSONObject) s;
                        AmazonOrderListProduct amazonOrderListProduct = new AmazonOrderListProduct();
                        Long IDP = IdWorker.getId(amazonOrderListProduct);
                        amazonOrderListProduct.setId(IDP);
                        amazonOrderListProduct.setParentAmazonOrderList(ID);
                        amazonOrderListProduct.setAsin(jsonObject1.getString("asin"));
                        amazonOrderListProduct.setQuantityOrdered(jsonObject1.getString("quantity_ordered"));
                        amazonOrderListProduct.setMsku(jsonObject1.getString("seller_sku"));
                        amazonOrderListProduct.setSku(jsonObject1.getString("local_sku"));
                        amazonOrderListProduct.setProductName(jsonObject1.getString("local_name"));
                        amazonOrderListProduct.setCreateTime(new Date());
                        amazonOrderListProduct.setLastUpdateTime(new Date());
                        Object p = redisTemplate.opsForValue().get("sku" + "_" + amazonOrderListProduct.getSku());
                        if (p != null) {
                            amazonOrderListProduct.setProductId(Long.parseLong(o.toString()));
                        } else {
                            QueryWrapper<Product> queryWrapper = new QueryWrapper();
                            queryWrapper.eq("sku", amazonOrderList.getSku());
                            Product product = productMapper.selectOne(queryWrapper);
                            if (product != null) {
                                amazonOrderListProduct.setProductId(product.getId());
                                redisTemplate.opsForValue().set("sku" + "_" + amazonOrderListProduct.getSku(), product.getId());
                            }
                        }
                        productList.add(amazonOrderListProduct);
//                        psProduct.setLong(1, IDP);
//                        psProduct.setLong(2, ID);
//                        psProduct.setString(3, jsonObject1.getString("asin"));
//                        psProduct.setString(4, jsonObject1.getString("quantity_ordered"));
//                        psProduct.setString(5, jsonObject1.getString("seller_sku"));
//                        psProduct.setString(6, jsonObject1.getString("local_sku"));
//                        psProduct.setString(7, jsonObject1.getString("local_name"));
//                        psProduct.setString(8, LocalDateUtils.getTodayNow());
//                        psProduct.setString(9, LocalDateUtils.getTodayNow());
//                        ppid.setString(1, jsonObject1.getString("local_sku"));
//                        ResultSet resultSet1 = ppid.executeQuery();
//                        Long pid = null;
//                        while (resultSet1.next()) {
//                            pid = resultSet1.getLong("id");
//                        }
//                        if (pid == null) {
//                            psProduct.setNull(10, Types.NULL);
//                        } else {
//                            psProduct.setLong(10, pid);
//                        }
//                        psProduct.addBatch();
                    }
                }
            }
//            ps.executeBatch();
//            psProduct.executeBatch();
//            conn.commit();

            //数据封装 分批次添加
            List<List<AmazonOrderList>> partition = Lists.partition(orderList, 300);
            for (List<AmazonOrderList> list : partition) {
                lingXingInterfaceMapper.insertOrder(list);
            }
            List<List<AmazonOrderListProduct>> partition1 = Lists.partition(productList, 500);
            for (List<AmazonOrderListProduct> list : partition1) {
                lingXingInterfaceMapper.insertOrderProduct(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (pd != null) {
                    pd.close();
                }
//                if (psid != null) {
//                    psid.close();
//                }
//                if (ppid != null) {
//                    ppid.close();
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//            JdbcUtils.close(conn, ps, psProduct);
        }
    }


    /**
     * 销售统计
     * event_date报表时间
     * asin_type查询维度2 msku
     * type类型2 销量
     * 按照店铺编码拉取指定月份报表时间数据
     *
     * @param year
     * @param month
     */
    @Override
    public void syncSalesDailyList(int year, int month) {
        Integer num = 0;
        QueryWrapper<ShopInfo> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT shop_code").lambda();
        List<ShopInfo> shopInfos = shopInfoService.list(wrapper);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1); // 注意：月份需要减1
        int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);//月的最大天数
        for (int i = 1; i <= maxDay; i++) {
            StringBuilder stringBuilder = new StringBuilder();
            List<ShopInfo> shopInfos1 = new ArrayList<>();
            shopInfos1.addAll(shopInfos);
            List<String> collect = new ArrayList<>();
            BoundedPriorityQueue<String> list = null;
            if (CollUtil.isNotEmpty(shopInfos1)) {
                collect = shopInfos1.stream().map(m -> m.getShopCode()).collect(Collectors.toList());
                list = new BoundedPriorityQueue<String>(collect.size());
                list.addAll(collect);
            }
            stringBuilder.append(year + "-" + month + "-");
            if (i < 10) {
                stringBuilder.append("0" + i);
            } else {
                stringBuilder.append(i);
            }
            System.out.println(stringBuilder);
            System.out.println(list + "++" + stringBuilder);
            for (String s : list) {
                int sid = Integer.parseInt(list.poll());
//                System.out.println(sid);
                String event_date = String.valueOf(stringBuilder);
                Integer length = 1000;
                Integer offset = 0;
                //获取token
                String token = getToken();
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("offset", offset);
                requestBody.put("length", length);
                requestBody.put("sid", sid);
                requestBody.put("event_date", event_date);
                requestBody.put("asin_type", 2);
                requestBody.put("type", 2);
                Map<String, Object> requestParams = new HashMap<>();
                //定义URL参数
                requestParams.put("access_token", token);
                requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams, SalesDailyList_URL,
                        null, requestBody);
                JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
                System.out.println("s------" + inventoryListResult);
                if (inventoryListResult.getIntValue("code") != 0) {
                    //inventoryListResult=new JSONObject();
                    inventoryListResult = regainLingXingData(inventoryListResult, requestBody, SalesDailyList_URL);
                }
                if (inventoryListResult.getIntValue("code") == 0) {
                    if (inventoryListResult.getIntValue("total") > 1000) {
                        Assert.isTrue(false, "查询仓库列表失败，原因：total超过1000");
                    }

                    num = num + inventoryListResult.getIntValue("total");
//                    System.out.println(inventoryListResult.getIntValue("total"));
                    saveSalesDailyList(inventoryListResult.getJSONArray("data"));
                } else {
                    Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
                }
            }
        }
        System.out.println(num);
    }

    @Override
    public void syncSalesDailyListByDay(JSONObject data) {
        Integer num = 0;
        QueryWrapper<ShopInfo> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT shop_code").lambda();
        List<ShopInfo> shopInfos = shopInfoService.list(wrapper);
        List<ShopInfo> shopInfos1 = new ArrayList<>();
        shopInfos1.addAll(shopInfos);
        List<String> collect = new ArrayList<>();
        BoundedPriorityQueue<String> list = null;
        if (CollUtil.isNotEmpty(shopInfos1)) {
            collect = shopInfos1.stream().map(m -> m != null && m.getShopCode() != null ? m.getShopCode() : "").collect(Collectors.toList());
            list = new BoundedPriorityQueue<String>(collect.size());
            list.addAll(collect);
        }
        for (String s : list) {
            String tmpStr = list.poll();
            int sid = 0;
            try {
                sid = Integer.parseInt(tmpStr == null || tmpStr.isEmpty() ? "0" : tmpStr);
            } catch (Exception e) {
                log.info("integer parseint error.");
                continue;
            }
//                System.out.println(sid);
            log.info("<" + tmpStr + "," + s + ", " + sid + " >");
            Integer length = 1000;
            Integer offset = 0;
            //获取token
            String token = getToken();
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("offset", offset);
            requestBody.put("length", length);
            requestBody.put("sid", sid);
            if (data != null && data.size() > 0) {
                requestBody.put("event_date", data.getString("day"));
            } else {
                requestBody.put("event_date", LocalDateUtils.getToday());
                log.info(LocalDateUtils.getToday());
            }
            requestBody.put("asin_type", 2);
            requestBody.put("type", 2);
            Map<String, Object> requestParams = new HashMap<>();
            //定义URL参数
            requestParams.put("access_token", token);
            requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
            requestParams.put("timestamp", System.currentTimeMillis() / 1000);
            //查询出库单列表
            Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    requestParams, SalesDailyList_URL,
                    null, requestBody);
            JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
            System.out.println("s------" + inventoryListResult);
            if (inventoryListResult.getIntValue("code") != 0) {
                //inventoryListResult=new JSONObject();
                inventoryListResult = regainLingXingData(inventoryListResult, requestBody, SalesDailyList_URL);
            }
            if (inventoryListResult.getIntValue("code") == 0) {
                if (inventoryListResult.getIntValue("total") > 1000) {
                    Assert.isTrue(false, "查询仓库列表失败，原因：total超过1000");
                }
                num = num + inventoryListResult.getIntValue("total");
//                    System.out.println(inventoryListResult.getIntValue("total"));
                saveSalesDailyList(inventoryListResult.getJSONArray("data"));
            } else {
//                Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
                log.error(s + "查询仓库列表失败，原因：code不为零查询失败");
            }
        }
        System.out.println(num);
    }

    @Override
    public void syncSalesDailyListByToDay() {
        Integer num = 0;
        QueryWrapper<ShopInfo> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT shop_code").lambda();
        List<ShopInfo> shopInfos = shopInfoService.list(wrapper);
        List<ShopInfo> shopInfos1 = new ArrayList<>();
        shopInfos1.addAll(shopInfos);
        List<String> collect = new ArrayList<>();
        BoundedPriorityQueue<String> list = null;
        if (CollUtil.isNotEmpty(shopInfos1)) {
            collect = shopInfos1.stream().map(m -> m.getShopCode()).collect(Collectors.toList());
            list = new BoundedPriorityQueue<String>(collect.size());
            list.addAll(collect);
        }
        for (String s : list) {
            int sid = Integer.parseInt(list.poll());
//                System.out.println(sid);
            Integer length = 1000;
            Integer offset = 0;
            //获取token
            String token = getToken();
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("offset", offset);
            requestBody.put("length", length);
            requestBody.put("sid", sid);
            requestBody.put("event_date", LocalDateUtils.getToday());
            requestBody.put("asin_type", 2);
            requestBody.put("type", 2);
            Map<String, Object> requestParams = new HashMap<>();
            //定义URL参数
            requestParams.put("access_token", token);
            requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
            requestParams.put("timestamp", System.currentTimeMillis() / 1000);
            //查询出库单列表
            Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    requestParams, SalesDailyList_URL,
                    null, requestBody);
            JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
            System.out.println("s------" + inventoryListResult);
            if (inventoryListResult.getIntValue("code") != 0) {
                //inventoryListResult=new JSONObject();
                inventoryListResult = regainLingXingData(inventoryListResult, requestBody, SalesDailyList_URL);
            }
            if (inventoryListResult.getIntValue("code") == 0) {
                if (inventoryListResult.getIntValue("total") > 1000) {
                    Assert.isTrue(false, "查询仓库列表失败，原因：total超过1000");
                }
                num = num + inventoryListResult.getIntValue("total");
//                    System.out.println(inventoryListResult.getIntValue("total"));
                saveSalesDailyList(inventoryListResult.getJSONArray("data"));
            } else {
                Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
            }
        }
        System.out.println(num);
    }

    @Override
    public void syncSalesDailyListByDayAndSid(int sid, String day) {
        Integer length = 1000;
        Integer offset = 0;
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("sid", 206);
        requestBody.put("event_date", "2023-07-01");
        requestBody.put("asin_type", 2);
        requestBody.put("type", 2);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, SalesDailyList_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        System.out.println("s------" + inventoryListResult);
        if (inventoryListResult.getIntValue("code") != 0) {
            //inventoryListResult=new JSONObject();
            inventoryListResult = regainLingXingData(inventoryListResult, requestBody, SalesDailyList_URL);
        }
        if (inventoryListResult.getIntValue("code") == 0) {
            if (inventoryListResult.getIntValue("total") > 1000) {
                Assert.isTrue(false, "查询仓库列表失败，原因：total超过1000");
            }
            saveSalesDailyList(inventoryListResult.getJSONArray("data"));
        } else {
            Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
        }
    }

    /**
     * 保存销售统计数据
     *
     * @param result
     */
    private void saveSalesDailyList(JSONArray result) {
        Connection conn = JdbcUtils.getConnnection();
        PreparedStatement ps = null;
        try {
            String sql = "INSERT INTO sales_daily_list(id,create_time,scode, bb_data, currency_code, " +
                    "asin, product_name, map_value) VALUES (?,?,?,?,?,?,?,?)";
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
            if (Objects.isNull(result)) {
                return;
            }
            for (Object o : result) {
                JSONObject object = (JSONObject) o;
                InventoryDetailOrderlist inventoryDetailOrderlist = new InventoryDetailOrderlist();
                long id = IdWorker.getId(inventoryDetailOrderlist);
                ps.setLong(1, id);
                ps.setString(2, LocalDateUtils.getTodayNow());
                ps.setString(3, object.getString("sid"));
                ps.setString(4, object.getString("r_date"));
                ps.setString(5, object.getString("currency_code"));
                ps.setString(6, object.getString("asin"));
                ps.setString(7, object.getString("product_name"));
                ps.setBigDecimal(8, object.getBigDecimal("map_value"));
                ps.addBatch();
            }
            ps.executeBatch();
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 亚马逊详情
     *
     * @param n
     * @param token
     */
    @Override
    public void syncAmazonOrderListDetail(int n, String token) {
        BoundedPriorityQueue amazonOrderID2 = getAmazonOrderID2(1);
        for (int q = 0; q < 10; q++) {
            JSONArray results = new JSONArray();
            for (int i = 0; i < 500; i++) {
                StringBuilder order_id = new StringBuilder();
                for (int j = 0; j < 200; j++) {
                    if (j != 0) {
                        order_id.append(",");
                    }
                    order_id.append(amazonOrderID2.poll());
                }
                JSONArray result = null;
                //定义分页参数
                Integer offset = 0;
                Integer length = 200;
                //定义查询参数
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("order_id", order_id);
                requestBody.put("offset", offset);
                requestBody.put("length", length);
                //定义URL参数
                Map<String, Object> requestParams = new HashMap<>();
                requestParams.put("access_token", token);
                requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams.put("timestamp", System.currentTimeMillis() / 1000);
                //查询列表
                Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams, AMAZONORDERLISTDETAIL_URL,
                        null, requestBody);
                JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
                if (inventoryListResult.getInteger("code") != 0) {
                    while (inventoryListResult.getInteger("code") != 0) {
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        token = getToken();
                        Map<String, Object> requestParams1 = new HashMap<>();
                        Map<String, Object> requestBody1 = new HashMap<>();
                        requestBody1.put("order_id", order_id);
                        requestBody1.put("offset", offset);
                        requestBody1.put("length", length);
                        requestParams1.put("access_token", token);
                        requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                        requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                        inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                                requestParams1, AMAZONORDERLISTDETAIL_URL,
                                null, requestBody1);
                        inventoryListResult = (JSONObject) inventoryListResultObj;
                    }
                }
                if (inventoryListResult.getInteger("code") == 0) {
                    result = inventoryListResult.getJSONArray("data");
                    for (int j = 0; j < result.size(); j++) {
                        JSONObject object = result.getJSONObject(j);
                        results.add(object);
                    }
                }
            }
//            saveAmazonOrderListDetail2(results);
//			拉取后续数据使用
            saveAmazonOrderListDetail(results);
        }
    }

    @Override
    public void syncAmazonOrderListDetail2(int n, String token) {
        BoundedPriorityQueue amazonOrderID2 = getAmazonOrderID2(1);
        for (int q = 0; q < 10; q++) {
            JSONArray results = new JSONArray();
            for (int i = 0; i < 500; i++) {
                StringBuilder order_id = new StringBuilder();
                for (int j = 0; j < 200; j++) {
                    if (j != 0) {
                        order_id.append(",");
                    }
                    order_id.append(amazonOrderID2.poll());
                }
                JSONArray result = null;
                //定义分页参数
                Integer offset = 0;
                Integer length = 200;
                //定义查询参数
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("order_id", order_id);
                requestBody.put("offset", offset);
                requestBody.put("length", length);
                //定义URL参数
                Map<String, Object> requestParams = new HashMap<>();
                requestParams.put("access_token", token);
                requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams.put("timestamp", System.currentTimeMillis() / 1000);
                //查询列表
                Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams, AMAZONORDERLISTDETAIL_URL,
                        null, requestBody);
                JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
                if (inventoryListResult.getInteger("code") != 0) {
                    while (inventoryListResult.getInteger("code") != 0) {
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        token = getToken();
                        Map<String, Object> requestParams1 = new HashMap<>();
                        Map<String, Object> requestBody1 = new HashMap<>();
                        requestBody1.put("order_id", order_id);
                        requestBody1.put("offset", offset);
                        requestBody1.put("length", length);
                        requestParams1.put("access_token", token);
                        requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                        requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                        inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                                requestParams1, AMAZONORDERLISTDETAIL_URL,
                                null, requestBody1);
                        inventoryListResult = (JSONObject) inventoryListResultObj;
                    }
                }
                if (inventoryListResult.getInteger("code") == 0) {
                    result = inventoryListResult.getJSONArray("data");
                    for (int j = 0; j < result.size(); j++) {
                        JSONObject object = result.getJSONObject(j);
                        results.add(object);
                    }
                }
            }
            saveAmazonOrderListDetail2(results);
        }
    }

    /**
     * 保存亚马逊详情数据直接插入
     *
     * @param result
     */
    private void saveAmazonOrderListDetail2(JSONArray result) {
        Connection conn = JdbcUtils.getConnnection();
        PreparedStatement ps = null;
        PreparedStatement psProduct = null;
        try {
            String sql = "INSERT INTO amazon_order_list_detail_copy1" +
                    "  (id, create_time, last_update_time," +
                    "   amazon_order_id, order_status, order_total_amount, fulfillment_channel," +
                    "   postal_code, phone, buyer_email, is_mcf_order, is_assessed, currency," +
                    "   sales_channel, purchase_date_local, purchase_date_local_utc, last_update_date," +
                    "   last_update_date_utc, earliest_ship_date, earliest_ship_date_utc, country, name," +
                    "   buyer_name, address_line1, is_return_order, is_replacement_order, is_replaced_order," +
                    "   is_business_order, shop_code, address, state_or_region, city, district," +
                    "   icon, country_code, address2, address3, taxes_included, shipping_address, " +
                    "   shipment_service_level_category, purchase_order_code," +
                    "   payment_method, cba_display_able_shipping_label, order_type, latest_ship_date," +
                    "   earliest_delivery_date, latest_delivery_date, number_of_items_shipped, " +
                    "   number_of_items_un_shipped, is_promotion, ship_service_level) " +
                    "  VALUES (?, ?, ?,?, ?, ?, ?,?, ?,?,?,?, ?,?,?, ?, ?,?, ?, ?, ?, " +
                    "?,?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?,?,?, ?,?, ?,?, ?, ?, ?, ?,?, ?, " +
                    "?, ?, ?, ?, ?)";
            String sqlP = "INSERT INTO amazon_order_list_product_detail_copy1" +
                    "  (id, create_time, asin," +
                    "   quantity_ordered, msku, product_id, product_name, sku, title, unit_price_amount," +
                    "   quantity_shipped, sales_price_amount, tax_amount, cg_price, profit," +
                    "   parent_amazon_order_list_detail, points_monetary_value_amount, item_price_amount, " +
                    "   item_tax_amount, shipping_price_amount, shipping_tax_amount," +
                    "   gift_wrap_price_amount, gift_wrap_tax_amount, shipping_discount_amount, " +
                    "   cod_fee_amount, promotion_ids, shipping_discount_tax_amount, promotion_discount_amount," +
                    "   promotion_discount_tax_amount, cod_fee_discount_amount, gift_message_text, condition_note, " +
                    "   condition_id, condition_subtype_id, scheduled_delivery_start_date, scheduled_delivery_end_date," +
                    "   price_designation, scode, fee_name, cg_transport_costs, fba_shipment_amount, commission_amount," +
                    "   other_amount, asin_url, fee_currency, fee_icon, fee_cost_amount, fee_cost, promotion_amount, item_discount)" +
                    "  VALUES (?,?,?,?," +
                    "?, ?, ?, ?, ?, ?," +
                    "?, ?, ?, ?, ?," +
                    "?, ? , ?, ?, " +
                    "?, ?,?, ?," +
                    "?, ?, ?, ?," +
                    "    ?, ?,?,?,?,?," +
                    "    ?, ?,?, ?, ?, ?,?,?, ?, ?, ?, ?, " +
                    "    ?, ?, ?, ?, ?)";
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
            psProduct = conn.prepareStatement(sqlP);
            if (Objects.isNull(result)) {
                return;
            }
            for (Object t : result) {
                JSONObject jsonObject = (JSONObject) t;
                AmazonOrderListDetail amazonOrderListDetail = new AmazonOrderListDetail();
                Long ID = IdWorker.getId(amazonOrderListDetail);
                ps.setLong(1, ID);
                ps.setString(2, LocalDateUtils.getTodayNow());
                ps.setString(3, LocalDateUtils.getTodayNow());
                ps.setString(4, jsonObject.getString("amazon_order_id"));
                ps.setString(5, jsonObject.getString("order_status"));
                ps.setString(6, jsonObject.getString("order_total_amount"));
                ps.setString(7, jsonObject.getString("fulfillment_channel"));
                ps.setString(8, jsonObject.getString("postal_code"));
                ps.setString(9, jsonObject.getString("phone"));
                ps.setString(10, jsonObject.getString("buyer_email"));
                ps.setString(11, jsonObject.getString("is_mcf_order"));
                ps.setString(12, jsonObject.getString("is_assessed"));
                ps.setString(13, jsonObject.getString("currency"));
                ps.setString(14, jsonObject.getString("sales_channel"));
                ps.setString(15, jsonObject.getString("purchase_date_local"));
                ps.setString(16, jsonObject.getString("purchase_date_local_utc"));
                ps.setString(17, jsonObject.getString("last_update_date"));
                ps.setString(18, jsonObject.getString("last_update_date_utc"));
                ps.setString(19, jsonObject.getString("earliest_ship_date"));
                ps.setString(20, jsonObject.getString("earliest_ship_date_utc"));
                ps.setString(21, jsonObject.getString("country"));
                ps.setString(22, jsonObject.getString("name"));
                ps.setString(23, jsonObject.getString("buyer_name"));
                ps.setString(24, jsonObject.getString("address_line1"));
                ps.setString(25, jsonObject.getString("is_return_order"));
                ps.setString(26, jsonObject.getString("is_replacement_order"));
                ps.setString(27, jsonObject.getString("is_replaced_order"));
                ps.setString(28, jsonObject.getString("is_business_order"));
                ps.setString(29, jsonObject.getString("sid"));
                ps.setString(30, jsonObject.getString("address"));
                ps.setString(31, jsonObject.getString("state_or_region"));
                ps.setString(32, jsonObject.getString("city"));
                ps.setString(33, jsonObject.getString("district"));
                ps.setString(34, jsonObject.getString("icon"));
                ps.setString(35, jsonObject.getString("country_code"));
                ps.setString(36, jsonObject.getString("address2"));
                ps.setString(37, jsonObject.getString("address3"));
                ps.setString(38, jsonObject.getString("taxes_included"));
                ps.setString(39, jsonObject.getString("shipping_address"));
                ps.setString(40, jsonObject.getString("shipment_service_level_category"));
                ps.setString(41, jsonObject.getString("purchase_order_number"));
                ps.setString(42, jsonObject.getString("payment_method"));
                ps.setString(43, jsonObject.getString("cba_display_able_shipping_label"));
                ps.setString(44, jsonObject.getString("order_type"));
                ps.setString(45, jsonObject.getString("latest_ship_date"));
                ps.setString(46, jsonObject.getString("earliest_delivery_date"));
                ps.setString(47, jsonObject.getString("latest_delivery_date"));
                ps.setString(48, jsonObject.getString("number_of_items_shipped"));
                ps.setString(49, jsonObject.getString("number_of_items_un_shipped"));
                ps.setString(50, jsonObject.getString("is_promotion"));
                ps.setString(51, jsonObject.getString("ship_service_level"));
                ps.addBatch();
                JSONArray amazonOrderDetailProducts = jsonObject.getJSONArray("item_list");
                if (Objects.nonNull(amazonOrderDetailProducts)) {
                    for (Object s : amazonOrderDetailProducts) {
                        JSONObject jsonObject1 = (JSONObject) s;
                        AmazonOrderListProductDetail amazonOrderListProductDetail = new AmazonOrderListProductDetail();
                        Long IDP = IdWorker.getId(amazonOrderListProductDetail);
                        psProduct.setLong(1, IDP);
                        psProduct.setString(2, LocalDateUtils.getTodayNow());
                        psProduct.setString(3, jsonObject1.getString("asin"));
                        psProduct.setString(4, jsonObject1.getString("quantity_ordered"));
                        psProduct.setString(5, jsonObject1.getString("msku"));
                        psProduct.setNull(6, Types.NULL);
                        psProduct.setString(7, jsonObject1.getString("product_name"));
                        psProduct.setString(8, jsonObject1.getString("sku"));
                        psProduct.setString(9, jsonObject1.getString("title"));
                        psProduct.setString(10, jsonObject1.getString("unit_price_amount"));
                        psProduct.setString(11, jsonObject1.getString("quantity_shipped"));
                        psProduct.setString(12, jsonObject1.getString("sales_price_amount"));
                        psProduct.setString(13, jsonObject1.getString("tax_amount"));
                        psProduct.setString(14, jsonObject1.getString("cg_price"));
                        psProduct.setString(15, jsonObject1.getString("profit"));
                        psProduct.setLong(16, ID);
                        psProduct.setString(17, jsonObject1.getString("points_monetary_value_amount"));
                        psProduct.setString(18, jsonObject1.getString(" item_price_amount"));
                        psProduct.setString(19, jsonObject1.getString("item_tax_amount"));
                        psProduct.setString(20, jsonObject1.getString("shipping_price_amount"));
                        psProduct.setString(21, jsonObject1.getString("shipping_tax_amount"));
                        psProduct.setString(22, jsonObject1.getString("gift_wrap_price_amount"));
                        psProduct.setString(23, jsonObject1.getString("gift_wrap_tax_amount"));
                        psProduct.setString(24, jsonObject1.getString("shipping_discount_amount"));
                        psProduct.setString(25, jsonObject1.getString("cod_fee_amount"));
                        psProduct.setString(26, jsonObject1.getString("promotion_ids"));
                        psProduct.setString(27, jsonObject1.getString("shipping_discount_tax_amount"));
                        psProduct.setString(28, jsonObject1.getString("promotion_discount_amount"));
                        psProduct.setString(29, jsonObject1.getString("promotion_discount_tax_amount"));
                        psProduct.setString(30, jsonObject1.getString("cod_fee_discount_amount"));
                        psProduct.setString(31, jsonObject1.getString("gift_message_text"));
                        psProduct.setString(32, jsonObject1.getString("condition_note"));
                        psProduct.setString(33, jsonObject1.getString("condition_id"));
                        psProduct.setString(34, jsonObject1.getString("condition_subtype_id"));
                        psProduct.setString(35, jsonObject1.getString("scheduled_delivery_start_date"));
                        psProduct.setString(36, jsonObject1.getString("scheduled_delivery_end_date"));
                        psProduct.setString(37, jsonObject1.getString("price_designation"));
                        psProduct.setString(38, jsonObject1.getString("sid"));
                        psProduct.setString(39, jsonObject1.getString("fee_name"));
                        psProduct.setString(40, jsonObject1.getString("cg_transport_costs"));
                        psProduct.setString(41, jsonObject1.getString("fba_shipment_amount"));
                        psProduct.setString(42, jsonObject1.getString("commission_amount"));
                        psProduct.setString(43, jsonObject1.getString("other_amount"));
                        psProduct.setString(44, jsonObject1.getString("asin_url"));
                        psProduct.setString(45, jsonObject1.getString("fee_currency"));
                        psProduct.setString(46, jsonObject1.getString("fee_icon"));
                        psProduct.setString(47, jsonObject1.getString("fee_cost_amount"));
                        psProduct.setString(48, jsonObject1.getString("fee_cost"));
                        psProduct.setString(49, jsonObject1.getString("promotion_amount"));
                        psProduct.setString(50, jsonObject1.getString("item_discount"));
                        psProduct.addBatch();
                    }
                }
            }
            ps.executeBatch();
            psProduct.executeBatch();
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(conn, ps, psProduct);
        }
    }

    /**
     * 保存亚马逊详情数据判断是否有重复
     *
     * @param result
     */
    private void saveAmazonOrderListDetail(JSONArray result) {
        Connection conn = JdbcUtils.getConnnection();
        PreparedStatement ps = null;
        PreparedStatement psProduct = null;
        PreparedStatement psid = null;
        PreparedStatement ppsid = null;
        PreparedStatement ppid = null;
        PreparedStatement pd = null;
        try {
            String sql = "INSERT INTO amazon_order_list_detail" +
                    "  (id, create_time, last_update_time," +
                    "   amazon_order_id, order_status, order_total_amount, fulfillment_channel," +
                    "   postal_code, phone, buyer_email, is_mcf_order, is_assessed, currency," +
                    "   sales_channel, purchase_date_local, purchase_date_local_utc, last_update_date," +
                    "   last_update_date_utc, earliest_ship_date, earliest_ship_date_utc, country, name," +
                    "   buyer_name, address_line1, is_return_order, is_replacement_order, is_replaced_order," +
                    "   is_business_order, shop_id, address, state_or_region, city, district," +
                    "   icon, country_code, address2, address3, taxes_included, shipping_address, " +
                    "   shipment_service_level_category, purchase_order_code," +
                    "   payment_method, cba_display_able_shipping_label, order_type, latest_ship_date," +
                    "   earliest_delivery_date, latest_delivery_date, number_of_items_shipped, " +
                    "   number_of_items_un_shipped, is_promotion, ship_service_level) " +
                    "  VALUES (?, ?, ?,?, ?, ?, ?,?, ?,?,?,?, ?,?,?, ?, ?,?, ?, ?, ?, " +
                    "?,?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?,?,?, ?,?, ?,?, ?, ?, ?, ?,?, ?, " +
                    "?, ?, ?, ?, ?)";
            String sqlP = "INSERT INTO amazon_order_list_product_detail" +
                    "  (id, create_time, asin," +
                    "   quantity_ordered, msku, product_id, product_name, sku, title, unit_price_amount," +
                    "   quantity_shipped, sales_price_amount, tax_amount, cg_price, profit," +
                    "   parent_amazon_order_list_detail, points_monetary_value_amount, item_price_amount, " +
                    "   item_tax_amount, shipping_price_amount, shipping_tax_amount," +
                    "   gift_wrap_price_amount, gift_wrap_tax_amount, shipping_discount_amount, " +
                    "   cod_fee_amount, promotion_ids, shipping_discount_tax_amount, promotion_discount_amount," +
                    "   promotion_discount_tax_amount, cod_fee_discount_amount, gift_message_text, condition_note, " +
                    "   condition_id, condition_subtype_id, scheduled_delivery_start_date, scheduled_delivery_end_date," +
                    "   price_designation, sid, fee_name, cg_transport_costs, fba_shipment_amount, commission_amount," +
                    "   other_amount, asin_url, fee_currency, fee_icon, fee_cost_amount, fee_cost, promotion_amount, item_discount)" +
                    "  VALUES (?,?,?,?," +
                    "?, ?, ?, ?, ?, ?," +
                    "?, ?, ?, ?, ?," +
                    "?, ? , ?, ?, " +
                    "?, ?,?, ?," +
                    "?, ?, ?, ?," +
                    "    ?, ?,?,?,?,?," +
                    "    ?, ?,?, ?, ?, ?,?,?, ?, ?, ?, ?, " +
                    "    ?, ?, ?, ?, ?)";
            String sqlShopId = "SELECT id FROM shop_info WHERE shop_code=? and del_flag=0";
            String sqlProductId = "SELECT id FROM product WHERE sku=? and del_flag=0";
            String sqlPd = "SELECT 1 FROM amazon_order_list_detail WHERE amazon_order_id=? and shop_id=? and del_flag=0";
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
            psProduct = conn.prepareStatement(sqlP);
            psid = conn.prepareStatement(sqlShopId);
            ppsid = conn.prepareStatement(sqlShopId);
            ppid = conn.prepareStatement(sqlProductId);
            pd = conn.prepareStatement(sqlPd);
            if (Objects.isNull(result)) {
                return;
            }
            for (Object t : result) {
                JSONObject jsonObject = (JSONObject) t;
                psid.setString(1, jsonObject.getString("sid"));
                ResultSet resultSet = psid.executeQuery();
                Long sid = null;
                while (resultSet.next()) {
                    sid = resultSet.getLong("id");
                }
                if (sid == null) {
                    ps.setNull(29, Types.NULL);//根据code查id
                } else {
                    ps.setLong(29, sid);//根据code查id
                }
                pd.setString(1, jsonObject.getString("amazon_order_id"));
                if (sid == null) {
                    pd.setNull(2, Types.NULL);
                } else {
                    pd.setLong(2, sid);
                }
                ResultSet resultSetpd = pd.executeQuery();
                int one = 0;
                while (resultSetpd.next()) {
                    one = resultSetpd.getInt("1");
                }
                System.out.println(one);
                if (one == 1) {
                    continue;
                }
                AmazonOrderListDetail amazonOrderListDetail = new AmazonOrderListDetail();
                Long ID = IdWorker.getId(amazonOrderListDetail);
                ps.setLong(1, ID);
                ps.setString(2, LocalDateUtils.getTodayNow());
                ps.setString(3, LocalDateUtils.getTodayNow());
                ps.setString(4, jsonObject.getString("amazon_order_id"));
                ps.setString(5, jsonObject.getString("order_status"));
                ps.setString(6, jsonObject.getString("order_total_amount"));
                ps.setString(7, jsonObject.getString("fulfillment_channel"));
                ps.setString(8, jsonObject.getString("postal_code"));
                ps.setString(9, jsonObject.getString("phone"));
                ps.setString(10, jsonObject.getString("buyer_email"));
                ps.setString(11, jsonObject.getString("is_mcf_order"));
                ps.setString(12, jsonObject.getString("is_assessed"));
                ps.setString(13, jsonObject.getString("currency"));
                ps.setString(14, jsonObject.getString("sales_channel"));
                ps.setString(15, jsonObject.getString("purchase_date_local"));
                ps.setString(16, jsonObject.getString("purchase_date_local_utc"));
                ps.setString(17, jsonObject.getString("last_update_date"));
                ps.setString(18, jsonObject.getString("last_update_date_utc"));
                ps.setString(19, jsonObject.getString("earliest_ship_date"));
                ps.setString(20, jsonObject.getString("earliest_ship_date_utc"));
                ps.setString(21, jsonObject.getString("country"));
                ps.setString(22, jsonObject.getString("name"));
                ps.setString(23, jsonObject.getString("buyer_name"));
                ps.setString(24, jsonObject.getString("address_line1"));
                ps.setString(25, jsonObject.getString("is_return_order"));
                ps.setString(26, jsonObject.getString("is_replacement_order"));
                ps.setString(27, jsonObject.getString("is_replaced_order"));
                ps.setString(28, jsonObject.getString("is_business_order"));
//				ps.setString(30,jsonObject.getString("sid"));//code
                ps.setString(30, jsonObject.getString("address"));
                ps.setString(31, jsonObject.getString("state_or_region"));
                ps.setString(32, jsonObject.getString("city"));
                ps.setString(33, jsonObject.getString("district"));
                ps.setString(34, jsonObject.getString("icon"));
                ps.setString(35, jsonObject.getString("country_code"));
                ps.setString(36, jsonObject.getString("address2"));
                ps.setString(37, jsonObject.getString("address3"));
                ps.setString(38, jsonObject.getString("taxes_included"));

                ps.setString(39, jsonObject.getString("shipping_address"));
                ps.setString(40, jsonObject.getString("shipment_service_level_category"));
                ps.setString(41, jsonObject.getString("purchase_order_number"));
//				ps.setString(41,jsonObject.getString("purchase_order_id"));
                ps.setString(42, jsonObject.getString("payment_method"));
                ps.setString(43, jsonObject.getString("cba_display_able_shipping_label"));
                ps.setString(44, jsonObject.getString("order_type"));
                ps.setString(45, jsonObject.getString("latest_ship_date"));
                ps.setString(46, jsonObject.getString("earliest_delivery_date"));
                ps.setString(47, jsonObject.getString("latest_delivery_date"));
                ps.setString(48, jsonObject.getString("number_of_items_shipped"));
                ps.setString(49, jsonObject.getString("number_of_items_un_shipped"));
                ps.setString(50, jsonObject.getString("is_promotion"));
                ps.setString(51, jsonObject.getString("ship_service_level"));
                ps.addBatch();
                JSONArray amazonOrderDetailProducts = jsonObject.getJSONArray("item_list");
                if (Objects.nonNull(amazonOrderDetailProducts)) {
                    for (Object s : amazonOrderDetailProducts) {
                        JSONObject jsonObject1 = (JSONObject) s;
                        AmazonOrderListProductDetail amazonOrderListProductDetail = new AmazonOrderListProductDetail();
                        Long IDP = IdWorker.getId(amazonOrderListProductDetail);
                        psProduct.setLong(1, IDP);
                        psProduct.setString(2, LocalDateUtils.getTodayNow());
//						psProduct.setString(3,LocalDateUtils.getTodayNow());
                        psProduct.setString(3, jsonObject1.getString("asin"));
                        psProduct.setString(4, jsonObject1.getString("quantity_ordered"));
                        psProduct.setString(5, jsonObject1.getString("msku"));
                        ppid.setString(1, jsonObject1.getString("sku"));
                        ResultSet ppidRest = ppid.executeQuery();
                        Long ppId = null;
                        while (ppidRest.next()) {
                            ppId = ppidRest.getLong("id");
                        }
                        if (ppId == null) {
                            psProduct.setNull(6, Types.NULL);
                        } else {
                            psProduct.setLong(6, ppId);
                        }
                        psProduct.setString(7, jsonObject1.getString("product_name"));
                        psProduct.setString(8, jsonObject1.getString("sku"));
                        psProduct.setString(9, jsonObject1.getString("title"));
                        psProduct.setString(10, jsonObject1.getString("unit_price_amount"));
                        psProduct.setString(11, jsonObject1.getString("quantity_shipped"));
                        psProduct.setString(12, jsonObject1.getString("sales_price_amount"));
                        psProduct.setString(13, jsonObject1.getString("tax_amount"));
                        psProduct.setString(14, jsonObject1.getString("cg_price"));
                        psProduct.setString(15, jsonObject1.getString("profit"));
                        psProduct.setLong(16, ID);
                        psProduct.setString(17, jsonObject1.getString("points_monetary_value_amount"));
                        psProduct.setString(18, jsonObject1.getString(" item_price_amount"));
                        psProduct.setString(19, jsonObject1.getString("item_tax_amount"));
                        psProduct.setString(20, jsonObject1.getString("shipping_price_amount"));
                        psProduct.setString(21, jsonObject1.getString("shipping_tax_amount"));
                        psProduct.setString(22, jsonObject1.getString("gift_wrap_price_amount"));
                        psProduct.setString(23, jsonObject1.getString("gift_wrap_tax_amount"));
                        psProduct.setString(24, jsonObject1.getString("shipping_discount_amount"));
                        psProduct.setString(25, jsonObject1.getString("cod_fee_amount"));
                        psProduct.setString(26, jsonObject1.getString("promotion_ids"));
                        psProduct.setString(27, jsonObject1.getString("shipping_discount_tax_amount"));
                        psProduct.setString(28, jsonObject1.getString("promotion_discount_amount"));
                        psProduct.setString(29, jsonObject1.getString("promotion_discount_tax_amount"));
                        psProduct.setString(30, jsonObject1.getString("cod_fee_discount_amount"));
                        psProduct.setString(31, jsonObject1.getString("gift_message_text"));
                        psProduct.setString(32, jsonObject1.getString("condition_note"));
                        psProduct.setString(33, jsonObject1.getString("condition_id"));
                        psProduct.setString(34, jsonObject1.getString("condition_subtype_id"));
                        psProduct.setString(35, jsonObject1.getString("scheduled_delivery_start_date"));
                        psProduct.setString(36, jsonObject1.getString("scheduled_delivery_end_date"));
                        psProduct.setString(37, jsonObject1.getString("price_designation"));
                        ppsid.setString(1, jsonObject1.getString("sid"));
                        ResultSet resultSet1 = ppsid.executeQuery();
                        Long sid2 = null;
                        while (resultSet1.next()) {
                            sid2 = resultSet1.getLong("id");
                        }
                        if (sid2 == null) {
                            psProduct.setNull(38, Types.NULL);//根据code查id
                        } else {
                            psProduct.setLong(38, sid2);//根据code查id
                        }
                        psProduct.setString(39, jsonObject1.getString("fee_name"));
                        psProduct.setString(40, jsonObject1.getString("cg_transport_costs"));
                        psProduct.setString(41, jsonObject1.getString("fba_shipment_amount"));
                        psProduct.setString(42, jsonObject1.getString("commission_amount"));
                        psProduct.setString(43, jsonObject1.getString("other_amount"));
                        psProduct.setString(44, jsonObject1.getString("asin_url"));
                        psProduct.setString(45, jsonObject1.getString("fee_currency"));
                        psProduct.setString(46, jsonObject1.getString("fee_icon"));
                        psProduct.setString(47, jsonObject1.getString("fee_cost_amount"));
                        psProduct.setString(48, jsonObject1.getString("fee_cost"));
                        psProduct.setString(49, jsonObject1.getString("promotion_amount"));
                        psProduct.setString(50, jsonObject1.getString("item_discount"));
                        psProduct.addBatch();
                    }
                }
            }
            ps.executeBatch();
            psProduct.executeBatch();
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (psid != null) {
                    psid.close();
                }
                if (ppsid != null) {
                    ppsid.close();
                }
                if (ppid != null) {
                    ppid.close();
                }
                if (pd != null) {
                    pd.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JdbcUtils.close(conn, ps, psProduct);
        }
    }

    //	拉取亚马逊详情后续数据使用
    public BoundedPriorityQueue getAmazonOrderID2(int current) {
        System.out.println(current);
        String amazonOrderId = "";
        Page<AmazonOrderList> page = new Page<>();
        page.setSize(Integer.MAX_VALUE);
        page.setCurrent(current);
        QueryWrapper<AmazonOrderList> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT amazon_order_id").lambda();
        Page<AmazonOrderList> page1 = amazonOrderListMapper.selectPage(page, wrapper);
        List<AmazonOrderList> records = page1.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            List<String> collect = page1.getRecords().stream().map(m -> m.getAmazonOrderId()).collect(Collectors.toList());
            BoundedPriorityQueue<String> list = new BoundedPriorityQueue<String>(collect.size());
            list.addAll(collect);
            return list;
        }
        return null;
    }

    //	拉取亚马逊详情后续数据使用
    public String getAmazonOrderID(int current) {
        System.out.println(current);
        String amazonOrderId = "";
        Page<AmazonOrderList> page = new Page<>();
        page.setSize(200);
        page.setCurrent(current);
        QueryWrapper<AmazonOrderList> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT amazon_order_id").lambda();
//		wrapper.orderByAsc("purchase_date_local");
        Page<AmazonOrderList> page1 = amazonOrderListMapper.selectPage(page, wrapper);
        for (AmazonOrderList a : page1.getRecords()) {
            amazonOrderId += a.getAmazonOrderId() + ",";
        }
        String substring = amazonOrderId.substring(0, amazonOrderId.length() - 1);
        return substring;
    }

    private static final Logger logger = LoggerFactory.getLogger("logger_task");
    private static String lxApiToken;
    @Autowired
    private RedisUtil redisTemplateUtil;
    private static final String SYNC_FLAG = "syncFlag";

    /**
     * listing
     */
    @Override
    public void syncListing() {
        long sync_start_time = System.currentTimeMillis();
        logger.info("listing同步开始");
        //判断是否存在listing同步被调用
        if (redisTemplateUtil.exists(SYNC_FLAG)) {
            logger.info("距离上一次任务执行不足两个小时或当前正在执行，不重复执行！");
            return;
        }
        redisTemplateUtil.insert(SYNC_FLAG, SYNC_FLAG, RedisUtil.CAHCEHOUR * 2);

        //创建临时表，存在则删除重新创建
        lingXingInterfaceMapper.createLingFatherTempTable();

        int batchNumber = 1;
        Integer length = 1000;
        Integer offset = 0;
        String shopCode = lingXingInterfaceMapper.getShopCode();
        this.lxApiToken = getToken();
        boolean runflag = true;
        offset = (batchNumber - 1) * length;

        while (runflag) {
            long request_start_time = System.currentTimeMillis();
            //查询列表
            try {
                //拉取数据
                logger.info("第 {} 批拉取开始", batchNumber);
                JSONObject jsonObject = pullLingxingData(offset, length, shopCode);
                logger.info("第 {} 批数据拉取结束! 用时: {} 毫秒",
                        batchNumber, System.currentTimeMillis() - request_start_time);
                JSONArray data = jsonObject.getJSONArray("data");
                if (data.size() != 0) {
                    //转换成存库
                    saveListing(data, batchNumber, sync_start_time);

                    //从上次的数据开始
                    offset = offset + data.size();

                } else {
                    runflag = false;
                    logger.info("获取不到数据，退出");
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                return;
            }
            logger.info("第 {} 批同步结束！ 耗费时间：{} 毫秒\n", batchNumber, System.currentTimeMillis() - request_start_time);
            batchNumber++;
        }

        //更新未更新状态数据为删除状态
        logger.info("更新未更新数据为删除状态");
        lingXingInterfaceMapper.updateDelListing(sync_start_time);
        logger.info("listing同步结束。总用时：{} 毫秒", System.currentTimeMillis() - sync_start_time);
    }

    private JSONObject pullLingxingData(Integer offset, Integer length, String shopCode) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("sid", shopCode);
        return tryRequestLingxingApi(requestBody, LISTING_URL);
    }

    private JSONObject tryRequestLingxingApi(Map<String, Object> requestBody, String apiUrl) {
        JSONObject resultJson = null;
        for (int i = 0; i < 10; ++i) {
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("access_token", this.lxApiToken);
            requestParams.put("app_key", APPID);
            requestParams.put("timestamp", System.currentTimeMillis() / 1000);

            resultJson = (JSONObject) restUtilLingXing.lingXingRequest(
                    "2",
                    RequestMethodKind.Post.getValue(),
                    requestParams, apiUrl,
                    null, requestBody
            );

            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                break;
            } else if (i == 10 - 1) {
                logger.info("拉取数据重试多次失败. Data=" + requestBody.toString() + "。Url=" + apiUrl);
            } else {
                logger.info("请求失败5秒后重试。" + resultJson.toJSONString());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    logger.info("系统程序异常", e);
                }
                if (code == 3001008 || code == 2001005) {
                    this.lxApiToken = getToken();
                    // MARK: log.output
                    logger.info(resultJson.toJSONString());
                }
            }
        }
        return resultJson;
    }

    /**
     * 查询保存产品sku和id的一一对应关系
     */
    private static Map<String, Long> productMap = new HashMap<>();

    private void saveProductMap(JSONArray result) {
        //将请求的数据中的sku提取出来并去重-> skus
        Set<String> uniqueSku = new HashSet<>();
        for (int i = 0; i < result.size(); i++) {
            JSONObject listing = result.getJSONObject(i);
            //提取sku
            String sku = listing.getString(ListingFatherTemp.SKU);
            uniqueSku.add(sku);
        }
        String[] skus = uniqueSku.toArray(new String[0]);

        //判断productMap中是否存在，不存在则存入newSkus中
        int temp = 0;
        String[] newSkus = new String[skus.length];
        for (int i = 0; i < skus.length; i++) {
            if (!productMap.containsKey(skus[i])) {
                newSkus[temp] = skus[i];
                temp++;
            }
        }

        //查询newSkus和id的对应关系并保存
        if (newSkus.length != 0) {
            List<Product> products = lingXingInterfaceMapper.getIdsBySkus(newSkus);
            //将product表中sku和id的关系存入productMap中
            for (Product product : products) {
                productMap.put(product.getSku(), product.getId());
            }
        }
    }

    /**
     * 查询并保存保存店铺sku和id的一一对应关系
     */
    private static Map<String, Long> shopMap = new HashMap<>();

    private void saveShopMap(JSONArray result) {
        //将请求的数据中的sid提取出来并去重-> uniqueCode
        Set<String> uniqueCode = new HashSet<>();
        for (int i = 0; i < result.size(); i++) {
            JSONObject listing = result.getJSONObject(i);
            //提取sku
            String sid = listing.getString(ListingFatherTemp.S_ID);
            uniqueCode.add(sid);
        }

        String[] codes = uniqueCode.toArray(new String[0]);
        //判断shopMap中是否存在，不存在则存入newCodes中
        int temp = 0;
        String[] newCode = new String[codes.length];
        for (int i = 0; i < codes.length; i++) {
            if (!shopMap.containsKey(codes[i])) {
                newCode[temp] = codes[i];
                temp++;
            }
        }

        //查询newCode和id的对应关系并保存
        if (newCode.length != 0) {
            List<ShopInfo> shopInfos = lingXingInterfaceMapper.getIdsByCodes(newCode);
            //将shopInfo表中shop_code和id的关系存入shopMap中
            for (ShopInfo shopInfo : shopInfos) {
                shopMap.put(shopInfo.getShopCode(), shopInfo.getId());
            }
        }
    }

    /**
     * 保存listing数据
     *
     * @param result
     */
    private void saveListing(JSONArray result, Integer batchNumber, Long syncFlag) {
        logger.info("第 {} 批同步开始", batchNumber);
        Long startTime = System.currentTimeMillis();
        if (Objects.isNull(result)) {
            return;
        }
        //保存product表中sku和id的一一对应关系
        saveProductMap(result);
        //保存shopInfo表中shop_code和id的一一对应关系
        saveShopMap(result);
        List<ListingFatherTemp> listingFathers = new ArrayList<>();
        //封装
        for (Object o : result) {
            JSONObject jsonObject = (JSONObject) o;
            ListingFatherTemp listingFather = new ListingFatherTemp(jsonObject);
            listingFather.setPairProduct(productMap.get(listingFather.getSku()) != null ? productMap.get(listingFather.getSku()) : null);
            listingFather.setShop(shopMap.get(listingFather.getShopCode()) != null ? shopMap.get(listingFather.getShopCode()) : null);
            listingFather.setBatchNumber(batchNumber);
            listingFather.setSyncFlag(syncFlag);
            listingFathers.add(listingFather);
        }
        //保存到临时表
        long save_start_time = System.currentTimeMillis();
        logger.info("第 {} 批，保存至临时表", batchNumber);
        lingXingInterfaceMapper.addListingFatherTemp(listingFathers);
        logger.info("第 {} 批保存结束，用时： {} 毫秒", batchNumber, System.currentTimeMillis() - save_start_time);
        //更新或新增，然后清除数据
        long updateOrInsert_start_time = System.currentTimeMillis();
        logger.info("第 {} 批，更新或新增开始", batchNumber);
        lingXingInterfaceMapper.syncListingFather(batchNumber);
        Long endTime = System.currentTimeMillis();
        logger.info("第 {} 批，更新或新增结束，用时：{} 毫秒", batchNumber, endTime - updateOrInsert_start_time);
    }

    @Override
    public void syncListingByShop(JSONObject data) {
        String token = getToken();
        Integer offset = 0;
        Integer length = 1000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("sid", data.getString("sid"));
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, LISTING_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
//        System.out.println(inventoryListResult);
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody, LISTING_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
//                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                log.error("查询Listing数据失败。");
                Assert.isTrue(false, "查询Listing数据失败。");
            }
        }
        //saveListing(inventoryListResult.getJSONArray("data"));
        //判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) inventoryListResult.get("total") - offset - length;
//        System.out.println(total);
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i <= pageNum; i++) {
                offset = offset + length;
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("sid", data.getString("sid"));
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, LISTING_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
//                System.out.println(inventoryListResult.getInteger("code") + ".........");
                if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                    JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, requestBody1, LISTING_URL);
                    if (jsonObject == null) {
                        return;
                    }
                    if (jsonObject.getInteger("code") == 0) {
                        continueSearchResultJSON = new JSONObject();
                        continueSearchResultJSON = jsonObject;
                    } else {
                        log.error("查询Listing数据失败。");
                        Assert.isTrue(false, "查询Listing数据失败。");
                    }
                }
                //转换成并存库
                //saveListing(continueSearchResultJSON.getJSONArray("data"));
            }
        }
    }

    /**
     * FBA库存数据
     */
    @Override
    public void syncFBAInventory() {
        Integer length = 10000;
        Integer offset = 0;
        String shopCode = lingXingInterfaceMapper.getShopCode();
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("sid", shopCode);
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, FBAInventory_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
//        System.out.println(inventoryListResult);
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody, FBAInventory_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                log.error("拉取FBA库存列表失败");
                Assert.isTrue(false, "拉取FBA库存列表失败");
            }
        }
//        int intValue = inventoryListResult.getJSONObject("data").getIntValue("total");
//        System.out.println(intValue);
        addFBAInventory(inventoryListResult.getJSONObject("data").getJSONArray("list"));
        //判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) inventoryListResult.getJSONObject("data").get("total") - offset - length;
        System.out.println(total);
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i <= pageNum; i++) {
                offset = offset + length;
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("sid", shopCode);
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, FBAInventory_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
//                System.out.println(inventoryListResult.getInteger("code") + ".........");
                if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                    JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, requestBody1, FBAInventory_URL);
                    if (jsonObject == null) {
                        return;
                    }
                    if (jsonObject.getInteger("code") == 0) {
                        continueSearchResultJSON = new JSONObject();
                        continueSearchResultJSON = jsonObject;
                    } else {
                        log.error("拉取FBA库存列表失败");
                        Assert.isTrue(false, "拉取FBA库存列表失败");
                    }
                }
//                System.out.println(continueSearchResultJSON.getJSONObject("data").getIntValue("total"));
                //转换成并存库
                addFBAInventory(continueSearchResultJSON.getJSONObject("data").getJSONArray("list"));
            }
        }
        //更新未更新状态数据为删除状态
        updateDelFbaInventory();
    }

    @Override
    public void syncFBAInventoryByShop(JSONObject data) {
        Integer length = 10000;
        Integer offset = 0;
//        String shopCode = lingXingInterfaceMapper.getShopCode();
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap<>();
//        requestBody.put("sid",shopCode);
        requestBody.put("sid", data.getString("sid"));
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, FBAInventory_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
//        System.out.println(inventoryListResult);
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody, FBAInventory_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                log.error("拉取FBA库存列表失败");
                Assert.isTrue(false, "拉取FBA库存列表失败");
            }
        }
//        int intValue = inventoryListResult.getJSONObject("data").getIntValue("total");
//        System.out.println(intValue);
        addFBAInventory(inventoryListResult.getJSONObject("data").getJSONArray("list"));
        //判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) inventoryListResult.getJSONObject("data").get("total") - offset - length;
        System.out.println(total);
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i <= pageNum; i++) {
                offset = offset + length;
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
//                requestBody1.put("sid", shopCode);
                requestBody1.put("sid", data.getString("sid"));
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, FBAInventory_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
//                System.out.println(inventoryListResult.getInteger("code") + ".........");
                if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                    JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, requestBody1, FBAInventory_URL);
                    if (jsonObject == null) {
                        return;
                    }
                    if (jsonObject.getInteger("code") == 0) {
                        continueSearchResultJSON = new JSONObject();
                        continueSearchResultJSON = jsonObject;
                    } else {
                        log.error("拉取FBA库存列表失败");
                        Assert.isTrue(false, "拉取FBA库存列表失败");
                    }
                }
//                System.out.println(continueSearchResultJSON.getJSONObject("data").getIntValue("total"));
                //转换成并存库
                addFBAInventory(continueSearchResultJSON.getJSONObject("data").getJSONArray("list"));
            }
        }
    }

    /**
     * 保存fba库存数据
     *
     * @param result
     */
    private void addFBAInventory(JSONArray result) {
//        int total = data.getIntValue("total");
//        System.out.println(total);
//        JSONArray result = data.getJSONArray("list");
        Connection conn = JdbcUtils.getConnnection();
        PreparedStatement ps = null;
        PreparedStatement psid = null;
        PreparedStatement ppid = null;
        PreparedStatement sel = null;
        PreparedStatement updateps = null;
        try {
            String sql = "INSERT INTO fba_inventory(id, create_time, asin, msku, fnsku, sku, " +
                    " total_inventory, available_stock, f_b_a_available_for_sale, f_b_m_available_for_sale," +
                    " warehouse_to_be_adjusted, during_warehouse_adjustment, to_be_shipped, planned_warehousing," +
                    " standard_in_transit, actual_in_transit, in_storage, not_available_for_sale, under_investigation," +
                    " day30, day60, day90, day180, day270, day330, day365, day366," +
                    " name,description," +
                    "wname,category_name,category_id,brand_name," +
                    "brand_id,stock_cost_total,cost,share_type,afn_fulfillable_quantity_multi,sid,trade_name)" +
                    " VALUES (?,?,?,?,?,?,?,?,?,?," +
                    "?,?,?,?,?,?,?,?,?,?," +
                    "?,?,?,?,?,?,?,?,?," +
                    "?,?,?,?,?,?,?,?,?,?,?)";
            String sqlShopId = "SELECT id FROM shop_info WHERE del_flag=0 and shop_code=?";
            String sqlProductId = "SELECT id FROM product WHERE del_flag=0 and sku=?";
            String sqlSel = "SELECT * from fba_inventory WHERE description=? and sku=? and fnsku=? and msku=? and asin=? and del_flag=0";
            String sqlUp = "UPDATE fba_inventory SET name = ?, sid = ?, last_update_time = ?,total_inventory = ?, available_stock = ?," +
                    " f_b_a_available_for_sale = ?, f_b_m_available_for_sale = ?, warehouse_to_be_adjusted = ?, " +
                    "during_warehouse_adjustment = ?, to_be_shipped = ?, planned_warehousing = ?, standard_in_transit = ?, " +
                    "actual_in_transit = ?, in_storage = ?, not_available_for_sale = ?, under_investigation = ?, day30 = ?," +
                    " day60 = ?, day90 = ?, day180 = ?, day270 = ?, day330 = ?, day365 = ?, day366 = ?, trade_name = ?, " +
                    "wname = ?, category_name = ?, category_id = ?, brand_name = ?, brand_id = ?, stock_cost_total = ?, " +
                    "cost = ?, share_type = ?, afn_fulfillable_quantity_multi = ? WHERE id = ?";
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
            psid = conn.prepareStatement(sqlShopId);
            ppid = conn.prepareStatement(sqlProductId);
            sel = conn.prepareStatement(sqlSel);
            updateps = conn.prepareStatement(sqlUp);
            if (Objects.isNull(result)) {
                return;
            }
            for (Object o : result) {
                JSONObject object = (JSONObject) o;
                ppid.setString(1, object.getString("sku"));
                ResultSet resultSet = ppid.executeQuery();
                String pid = null;
                while (resultSet.next()) {
                    pid = String.valueOf(resultSet.getLong("id"));
                }
                if (pid == null) {
                    ps.setNull(40, Types.NULL);
                    updateps.setNull(25, Types.NULL);
                } else {
                    ps.setString(40, pid);
                    updateps.setString(25, pid);
                }
                psid.setString(1, object.getString("sid"));
                ResultSet resultSet1 = psid.executeQuery();
                String sid = null;
                while (resultSet1.next()) {
                    sid = String.valueOf(resultSet1.getLong("id"));
                }
                if (sid == null) {
                    ps.setNull(39, Types.NULL);
                    updateps.setNull(2, Types.NULL);
                } else {
                    ps.setString(39, sid);
                    updateps.setString(2, sid);
                }
                sel.setString(1, object.getString("sid"));
                sel.setString(2, object.getString("sku"));
                sel.setString(3, object.getString("fnsku"));
                sel.setString(4, object.getString("msku"));
                sel.setString(5, object.getString("asin"));
                ResultSet resultSet2 = sel.executeQuery();
                Long selId = null;
                while (resultSet2.next()) {
                    selId = resultSet2.getLong("id");
                }
                if (selId == null) {
//                    新增
                    FBAInventory fbaInventory = new FBAInventory();
                    long id = IdWorker.getId(fbaInventory);
                    ps.setLong(1, id);
                    ps.setString(2, LocalDateUtils.getTodayNow());
                    ps.setString(3, object.getString("asin"));
                    ps.setString(4, object.getString("msku"));
                    ps.setString(5, object.getString("fnsku"));
                    ps.setString(6, object.getString("sku"));
                    ps.setInt(7, object.getIntValue("total_fulfillable_quantity"));//总库存
                    ps.setNull(8, Types.NULL);//available_stock可用库存
                    ps.setInt(9, object.getIntValue("afn_fulfillable_quantity"));//f_b_a_available_for_sale fba可售afn_fulfillable_quantity
                    ps.setNull(10, Types.NULL);//f_b_m_available_for_sale fbm可售
                    ps.setInt(11, object.getIntValue("reserved_fc_transfers"));//待调仓数量
                    ps.setInt(12, object.getIntValue("reserved_fc_processing"));//调仓中
                    ps.setInt(13, object.getIntValue("reserved_customerorders"));//待发货
                    ps.setInt(14, object.getIntValue("afn_inbound_working_quantity"));//计划入库
                    ps.setInt(15, object.getIntValue("afn_inbound_shipped_quantity"));//在途
                    ps.setInt(16, object.getIntValue("afn_erp_real_shipped_quantity"));//实际在途
                    ps.setInt(17, object.getIntValue("afn_inbound_receiving_quantity"));//入库中
                    ps.setInt(18, object.getIntValue("afn_unsellable_quantity"));//不可售
                    ps.setInt(19, object.getIntValue("afn_researching_quantity"));//调查中
                    ps.setInt(20, object.getIntValue("inv_age_0_to_30_days"));//30天库龄
                    ps.setInt(21, object.getIntValue("inv_age_31_to_60_days"));//31-60天库龄
                    ps.setInt(22, object.getIntValue("inv_age_61_to_90_days"));//61-90天库龄
                    ps.setInt(23, object.getIntValue("inv_age_91_to_180_days"));//91-180天库龄
                    ps.setInt(24, object.getIntValue("inv_age_181_to_270_days"));//181-270天库龄
                    ps.setInt(25, object.getIntValue("inv_age_271_to_330_days"));//271-330天库龄
                    ps.setInt(26, object.getIntValue("inv_age_331_to_365_days"));//331-365天库龄
                    ps.setInt(27, object.getIntValue("inv_age_365_plus_days"));//365天以上库龄
                    ps.setString(28, object.getString("product_name"));//品名
                    ps.setString(29, object.getString("sid"));//店铺编号
                    ps.setString(30, object.getString("wname"));//仓库名
                    ps.setString(31, object.getString("category_name"));//分类名称
                    ps.setString(32, object.getString("category_id"));//分类Id
                    ps.setString(33, object.getString("brand_name"));//品牌名称
                    ps.setString(34, object.getString("brand_id"));//品牌id
                    ps.setString(35, object.getString("stock_cost_total"));//货值
                    ps.setString(36, object.getString("cost"));//库存成本
                    ps.setString(37, object.getString("share_type"));//共享类型：0 非共享  1 北美共享   2 欧洲共享
                    ps.setString(38, object.getString("afn_fulfillable_quantity_multi"));//欧洲共享的多国店铺列表
                    ps.addBatch();
                } else {
//                    更新
                    updateps.setString(1, object.getString("product_name"));
                    updateps.setString(3, LocalDateUtils.getTodayNow());
                    updateps.setInt(4, object.getIntValue("total_fulfillable_quantity"));//总库存
                    updateps.setNull(5, Types.NULL);//available_stock可用库存
                    updateps.setInt(6, object.getIntValue("afn_fulfillable_quantity"));//f_b_a_available_for_sale fba可售afn_fulfillable_quantity
                    updateps.setNull(7, Types.NULL);//f_b_m_available_for_sale fbm可售
                    updateps.setInt(8, object.getIntValue("reserved_fc_transfers"));//待调仓数量
                    updateps.setInt(9, object.getIntValue("reserved_fc_processing"));//调仓中
                    updateps.setInt(10, object.getIntValue("reserved_customerorders"));//待发货
                    updateps.setInt(11, object.getIntValue("afn_inbound_working_quantity"));//计划入库
                    updateps.setInt(12, object.getIntValue("afn_inbound_shipped_quantity"));//在途
                    updateps.setInt(13, object.getIntValue("afn_erp_real_shipped_quantity"));//实际在途
                    updateps.setInt(14, object.getIntValue("afn_inbound_receiving_quantity"));//入库中
                    updateps.setInt(15, object.getIntValue("afn_unsellable_quantity"));//不可售
                    updateps.setInt(16, object.getIntValue("afn_researching_quantity"));//调查中
                    updateps.setInt(17, object.getIntValue("inv_age_0_to_30_days"));//30天库龄
                    updateps.setInt(18, object.getIntValue("inv_age_31_to_60_days"));//31-60天库龄
                    updateps.setInt(19, object.getIntValue("inv_age_61_to_90_days"));//61-90天库龄
                    updateps.setInt(20, object.getIntValue("inv_age_91_to_180_days"));//91-180天库龄
                    updateps.setInt(21, object.getIntValue("inv_age_181_to_270_days"));//181-270天库龄
                    updateps.setInt(22, object.getIntValue("inv_age_271_to_330_days"));//271-330天库龄
                    updateps.setInt(23, object.getIntValue("inv_age_331_to_365_days"));//331-365天库龄
                    updateps.setInt(24, object.getIntValue("inv_age_365_plus_days"));//365天以上库龄
                    updateps.setString(26, object.getString("wname"));//仓库名
                    updateps.setString(27, object.getString("category_name"));//分类名称
                    updateps.setString(28, object.getString("category_id"));//分类Id
                    updateps.setString(29, object.getString("brand_name"));//品牌名称
                    updateps.setString(30, object.getString("brand_id"));//品牌id
                    updateps.setString(31, object.getString("stock_cost_total"));//货值
                    updateps.setString(32, object.getString("cost"));//库存成本
                    updateps.setString(33, object.getString("share_type"));//共享类型：0 非共享  1 北美共享   2 欧洲共享
                    updateps.setString(34, object.getString("afn_fulfillable_quantity_multi"));//欧洲共享的多国店铺列表
                    updateps.setLong(35, selId);
                    updateps.addBatch();
                }
            }
            ps.executeBatch();
            updateps.executeBatch();
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (psid != null) {
                    psid.close();
                }
                if (ppid != null) {
                    ppid.close();
                }
                if (updateps != null) {
                    updateps.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JdbcUtils.close(conn, ps, sel);
        }
    }

    /**
     * 更新fba库存未更新状态数据为删除状态
     */
    private void updateDelFbaInventory() {
        Connection conn = JdbcUtils.getConnnection();
        PreparedStatement upd = null;
        String sqlupd = "UPDATE fba_inventory set del_flag=b'1' WHERE (last_update_time is null OR last_update_time< ?) and create_time< ? and del_flag=b'0'";
        try {
            upd = conn.prepareStatement(sqlupd);
            upd.setString(1, LocalDateUtils.getToday());
            upd.setString(2, LocalDateUtils.getToday());
            upd.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    //==========================================================

    @Override
    public void syncProductInfo(String sku, Integer id) {
        //获取token
        String token = getToken();

        if (sku == null && id == null) {
            return;
        }
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        if (id != null) {
            requestBody.put("id", id);
        }
        if (sku != null) {
            requestBody.put("sku", sku);
        }
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //产品详情
        Object productInfoResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, PRODUCT_INFO_URL,
                null, requestBody);
        JSONObject productInfoResult = (JSONObject) productInfoResultObj;
        if (!"0".equals(productInfoResult.get("code").toString())) {
            Assert.isTrue(false, "查询产品详情失败，原因：" + productInfoResult.get("msg").toString());
        }
        JSONObject result = productInfoResult.getJSONObject("data");
        try {
            handleProductInfoResult(result);
        } catch (Exception e) {
            log.info("产品入库失败---------", e.getMessage());
        }
    }


    @Override
    public void syncProductInfoBatch(String sku) {
        Assert.isTrue(StrUtil.isNotBlank(sku) && !sku.equals("{}"), "参数SKU不能为空");
        log.info("--------------" + sku);
        syncProductBase(sku, null, null);
    }


    /**
     * 根据时间同步并更新产品
     */
    @Override
    public void syncByTimeProduct(JSONObject object) {
        Map<String, Object> formData = MapUtil.get(object, "formData", Map.class);
        Assert.isTrue(MapUtil.isNotEmpty(formData), "参数不能为空");
        syncProductBase(null, MapUtil.getStr(formData, "time"), MapUtil.getStr(formData, "updateTime"));
    }


    private void syncProductBase(String sku, String createTime, String updateTime) {
        if (StrUtil.isAllEmpty(sku, createTime, updateTime)) {
            Assert.isTrue(false, "参数异常!");
        }
        JSONObject body = new JSONObject();
        if (StrUtil.isNotBlank(sku) && !StrUtil.equals(sku, "{}")) {
            List<String> skus = StrUtil.split(StrUtil.unWrap(sku, "{sku=", "}"), ",");
            body.put("sku_list", skus);
        }
        if (StrUtil.isNotBlank(createTime)) {
            long createTimeStart = DateUtil.beginOfDay(DateUtil.parseDate(createTime)).getTime() / 1000;
            long createTimeEnd = DateUtil.endOfDay((DateUtil.parseDate(createTime))).getTime() / 1000;
            body.put("create_time_start", createTimeStart);
            body.put("create_time_end", createTimeEnd);
        }
        if (StrUtil.isNotBlank(updateTime)) {
            long updateTimeStart = DateUtil.beginOfDay(DateUtil.parseDate(updateTime)).getTime() / 1000;
            long updateTimeEnd = DateUtil.endOfDay((DateUtil.parseDate(updateTime))).getTime() / 1000;
            body.put("create_time_start", updateTimeStart);
            body.put("create_time_end", updateTimeEnd);
        }
        SpringUtil.getBean(SyncProductListServiceImpl.class).mainLoop(body);
        List<TmpSyncLingxingToProduct> list = SpringUtil.getBean(TmpSyncLingxingToProductServiceImpl.class).list();
        if (CollUtil.isNotEmpty(list)) {
            JSONObject bodyInfo = new JSONObject();
            bodyInfo.put("skus", list.stream().map(m -> m.getSku()).collect(Collectors.toList()));
            SpringUtil.getBean(SyncLxBatchProductInfoServiceImpl.class).mainLoop(bodyInfo);
        }
        log.info("同步" + sku.toString() + "产品信息.");
    }


    private void handleProductInfoResult(JSONObject result) throws Exception {
        if (Objects.isNull(result)) {
            return;
        }
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
//		result.forEach(t -> {
//        for (Object t : result) {
        JSONObject product = (JSONObject) result;
        String picUrl = product.getString("pic_url");
        String sku = product.getString("sku");
        if (org.apache.commons.lang3.StringUtils.isNotBlank(sku)) {
            Product one = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, sku));
            if (null != one) {
                ProductVo products = new ProductVo();
                BeanUtils.copyProperties(one, products);
                products.setName(product.get("product_name").toString());
                products.setSku(product.get("sku").toString());
                products.setProcurementCost(product.getBigDecimal("cg_price"));
//                    products.setModel(product.getString("model"));
                products.setLastUpdateTime(products.getCreateTime());
//                    products.setPicUrl(updateUrl(sku, picUrl));
                if (jwtUserInfo != null) {
                    products.setCreateUser(jwtUserInfo.getUserId());
                    products.setLastUpdateUser(jwtUserInfo.getUserId());
                }
                products.setClassify(product.getLong("cid"));
                products.setProductType(product.getString("category_name"));
                products.setBrand(product.getLong("bid"));
                products.setTradeName(product.getString("brand_name"));
                products.setPurchasingDeliveryTime(product.getInteger("cg_delivery"));
                products.setTransportCost(product.getBigDecimal("cg_transport_costs"));
                products.setRemarks(product.getString("purchase_remark"));
                if (product.getInteger("status") == 0) {
                    products.setSalesStatus("CP04");
                }
                if (product.getInteger("status") == 1) {
                    products.setSalesStatus("CP02");
                }
                if (product.getInteger("status") == 2) {
                    products.setSalesStatus("CP01");
                }
                if (product.getInteger("status") == 3) {
                    products.setSalesStatus("CP03");
                }
                products.setIsCombo(product.getInteger("is_combo") == 0 ? false : true);
                products.setDeveloper(product.getLong("product_developer_uid"));
                products.setBuyer(product.getLong("cg_opt_uid"));
                //图片处理
                List<SysFile> fileList = new ArrayList<>();
                if (product.get("pic_url") != null && org.apache.commons.lang3.StringUtils.isNotBlank(product.getString("pic_url"))) {
                    MultipartFile multipartFile = onlineAddressTransferFile(product.getString("pic_url"));
                    fileList.add(fileService.upload(multipartFile, null));
                    products.setPicUrl(fileList);
                }
                products.setSupplierQuote(JSON.toJSONString(product.get("supplier_quote")));
                try {
                    productService.update(products);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Product products = new ProductVo();
                products.setName(product.get("product_name").toString());
                products.setSku(product.get("sku").toString());
                products.setProcurementCost(product.getBigDecimal("cg_price"));
//                    products.setPicUrl(updateUrl(sku, picUrl));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Long timeStamp = Long.valueOf(product.get("create_time").toString() + "000");
                String create_time = sdf.format(timeStamp);
                try {
                    products.setCreateTime(sdf.parse(create_time));
                    products.setLastUpdateTime(products.getCreateTime());
                } catch (ParseException e) {
                    Assert.isTrue(false, "日期转换失败");
                }
                if (jwtUserInfo != null) {
                    products.setCreateUser(jwtUserInfo.getUserId());
                    products.setLastUpdateUser(jwtUserInfo.getUserId());
                }
                products.setClassify(product.getLong("cid"));
                products.setProductType(product.getString("category_name"));
                products.setBrand(product.getLong("bid"));
                products.setTradeName(product.getString("brand_name"));
                //图片处理
                List<SysFile> fileList = new ArrayList<>();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(product.getString("pic_url"))) {
                    MultipartFile multipartFile = onlineAddressTransferFile(product.getString("pic_url"));
                    fileList.add(fileService.upload(multipartFile, null));
                    products.setPicUrl(fileList);
                }
                products.setPurchasingDeliveryTime(product.getInteger("cg_delivery"));
                products.setTransportCost(product.getBigDecimal("cg_transport_costs"));
                products.setRemarks(product.getString("purchase_remark"));
                if (product.getInteger("status") == 0) {
                    products.setSalesStatus("CP04");
                }
                if (product.getInteger("status") == 1) {
                    products.setSalesStatus("CP02");
                }
                if (product.getInteger("status") == 2) {
                    products.setSalesStatus("CP01");
                }
                if (product.getInteger("status") == 3) {
                    products.setSalesStatus("CP03");
                }
                products.setIsCombo(product.getInteger("is_combo") == 0 ? false : true);
                products.setDeveloper(product.getLong("product_developer_uid"));
                products.setBuyer(product.getLong("cg_opt_uid"));
                products.setSupplierQuote(JSON.toJSONString(product.get("supplier_quote")));
                productMapper.insert(products);
            }
        }
    }


    private void handleProductInfoResultBatch(JSONArray array) {
        if (Objects.isNull(array)) {
            return;
        }
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
        for (Object o : array) {
            JSONObject product = JSONObject.parseObject(o.toString());
            if (lingXingInterfaceMapper.checkSku(product.get("sku").toString()) == 0) {
                Product products = new ProductVo();
                products.setName(product.get("product_name").toString());
                products.setSku(product.get("sku").toString());
                products.setProcurementCost(product.getBigDecimal("cg_price"));
//                    products.setPicUrl(updateUrl(sku, picUrl));
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Long timeStamp = Long.valueOf(product.get("create_time").toString() + "000");
//                String create_time = sdf.format(timeStamp);
//                try {
//                    products.setCreateTime(sdf.parse(create_time));
////                    products.setLastUpdateTime(products.getCreateTime());
//                    products.setLastUpdateTime(new Date());
//                } catch (ParseException e) {
//                    Assert.isTrue(false, "日期转换失败");
//                }
                products.setCreateTime(new Date());
                products.setLastUpdateTime(new Date());
                if (jwtUserInfo != null) {
                    products.setCreateUser(jwtUserInfo.getUserId());
                    products.setLastUpdateUser(jwtUserInfo.getUserId());
                }
                products.setClassify(product.getLong("cid"));
                products.setProductType(product.getString("category_name"));
                products.setBrand(product.getLong("bid"));
                products.setTradeName(product.getString("brand_name"));
                //图片处理
                List<SysFile> fileList = new ArrayList<>();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(product.getString("pic_url"))) {
                    try {
                        MultipartFile multipartFile = onlineAddressTransferFile(product.getString("pic_url"));
                        fileList.add(fileService.upload(multipartFile, null));
                        products.setPicUrl(fileList);
                    } catch (Exception e) {
                    }
                }
                products.setPurchasingDeliveryTime(product.getInteger("cg_delivery"));
                products.setTransportCost(product.getBigDecimal("cg_transport_costs"));
                products.setRemarks(product.getString("purchase_remark"));
                if (product.getInteger("status") == 0) {
                    products.setSalesStatus("CP04");
                }
                if (product.getInteger("status") == 1) {
                    products.setSalesStatus("CP02");
                }
                if (product.getInteger("status") == 2) {
                    products.setSalesStatus("CP01");
                }
                if (product.getInteger("status") == 3) {
                    products.setSalesStatus("CP03");
                }
                products.setType("CP01");
                products.setIsCombo(product.getInteger("is_combo") == 0 ? false : true);
                products.setDeveloper(product.getLong("product_developer_uid"));
                products.setBuyer(product.getLong("cg_opt_uid"));
                products.setSupplierQuote(JSON.toJSONString(product.get("supplier_quote")));
                productMapper.insert(products);
            } else {
                Long id = null;
                id = lingXingInterfaceMapper.getIdBySku(product.get("sku").toString());
                Product products = new ProductVo();
//                if (id == null) {
//                    continue;
//                }
                products.setId(id);
                products.setName(product.get("product_name").toString());
                products.setSku(product.get("sku").toString());
                products.setProcurementCost(product.getBigDecimal("cg_price"));
//                    products.setModel(product.getString("model"));
//                products.setLastUpdateTime(products.getCreateTime());
                products.setLastUpdateTime(new Date());
//                    products.setPicUrl(updateUrl(sku, picUrl));
                if (jwtUserInfo != null) {
                    products.setCreateUser(jwtUserInfo.getUserId());
                    products.setLastUpdateUser(jwtUserInfo.getUserId());
                }
                products.setClassify(product.getLong("cid"));
                products.setProductType(product.getString("category_name"));
                products.setBrand(product.getLong("bid"));
                products.setTradeName(product.getString("brand_name"));
                products.setPurchasingDeliveryTime(product.getInteger("cg_delivery"));
                products.setTransportCost(product.getBigDecimal("cg_transport_costs"));
                products.setRemarks(product.getString("purchase_remark"));
                if (product.getInteger("status") == 0) {
                    products.setSalesStatus("CP04");
                }
                if (product.getInteger("status") == 1) {
                    products.setSalesStatus("CP02");
                }
                if (product.getInteger("status") == 2) {
                    products.setSalesStatus("CP01");
                }
                if (product.getInteger("status") == 3) {
                    products.setSalesStatus("CP03");
                }
                products.setType("CP01");
                products.setIsCombo(product.getInteger("is_combo") == 0 ? false : true);
                products.setDeveloper(product.getLong("product_developer_uid"));
                products.setBuyer(product.getLong("cg_opt_uid"));
                //图片处理
                List<SysFile> fileList = new ArrayList<>();
                if (product.get("pic_url") != null && org.apache.commons.lang3.StringUtils.isNotBlank(product.getString("pic_url"))) {
                    try {
                        MultipartFile multipartFile = onlineAddressTransferFile(product.getString("pic_url"));
                        SysFile upload = fileService.upload(multipartFile, null);
                        fileList.add(upload);
                        products.setPicUrl(fileList);
                    } catch (Exception e) {
                    }
                }
                products.setSupplierQuote(JSON.toJSONString(product.get("supplier_quote")));
                try {
                    productMapper.updateById(products);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


    }

    @Override
    public void syncStockIn() {
        //获取token
        String token = getToken();
        Date lastUpdateTime = stockInService.searchLastUpdateTime(new StockInSearchParamPo());
        //查询入库单最后更新时间
        long lastUpdateTimeStamp = null != lastUpdateTime ? lastUpdateTime.getTime() / 1000 : 1541575627L;
        //定义分页参数
        Integer offset = 0;
        Integer length = 200;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("search_field_time", "create_time");
        requestBody.put("start_date", lastUpdateTimeStamp);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询入库单列表
        Object stockInListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, STOCK_IN_LIST_URL,
                null, requestBody);
        JSONObject stockInListResult = (JSONObject) stockInListResultObj;
        if (!"0".equals(stockInListResult.get("code").toString())) {
            Assert.isTrue(false, "查询入库单列表失败，原因：" + stockInListResult.get("msg").toString());
        }
        JSONArray result = stockInListResult.getJSONArray("data");
        //转换成并存库
        handleStockInResult(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) stockInListResult.get("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                requestBody.put("offset", offset);
                //查询入库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams, STOCK_IN_LIST_URL,
                        null, requestBody);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                    Assert.isTrue(false, "查询入库单列表失败，原因：" + continueSearchResultJSON.get("msg").toString());
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成并存库
                handleStockInResult(continueSearchResult);
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void syncStockOutToday() {
        //获取token
        String token = getToken();
        Date lastUpdateTime = stockOutService.searchLastUpdateTime(new StockOutSearchParamPo());
        //查询出库单最后更新时间
        long lastUpdateTimeStamp = 1541575627L;
        //定义分页参数
        Integer offset = 0;
        Integer length = 200;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("search_field_time", "create_time");
        requestBody.put("status", 40);
        requestBody.put("type", 12);
        Calendar calendar = Calendar.getInstance();
        requestBody.put("start_date", new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(calendar.getTime()));
        requestBody.put("end_date", new SimpleDateFormat("yyyy-MM-dd 23:59:59").format(calendar.getTime()));
//        if (null != lastUpdateTime) {
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(lastUpdateTime);
//            calendar.add(Calendar.DATE, 1);
//            requestBody.put("start_date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
//        } else {
//            requestBody.put("start_date", new SimpleDateFormat("yyyy-MM-dd").format(lastUpdateTimeStamp));
//        }
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object stockOutListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, STOCK_OUT_LIST_URL,
                null, requestBody);
        JSONObject stockOutListResult = (JSONObject) stockOutListResultObj;
        if (!isNumeric(stockOutListResult.get("code").toString()) || (Integer.parseInt(stockOutListResult.get("code").toString()) != 0)) {
            Assert.isTrue(false, "查询出库单列表失败，原因：" + stockOutListResult.get("msg").toString());
        }
        JSONArray result = stockOutListResult.getJSONArray("data");
        //防止重复拉取数据，先删数据
        if (Objects.nonNull(result)) {
            lingXingInterfaceMapper.deleteByStartDate1(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
            log.info("delete by start date = " + new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
        }
        //转换成并存库
        handleStockOutResult(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) stockOutListResult.get("total");
        log.info("total is " + total);
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                log.info("result " + i + "/" + pageNum);
                offset = i * length;
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", requestBody.get("length"));
                requestBody1.put("search_field_time", requestBody.get("search_field_time"));
                requestBody1.put("start_date", requestBody.get("start_date"));
                requestBody1.put("status", requestBody.get("status"));
                requestBody1.put("type", "12");
                String token1 = getToken();
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token1);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, STOCK_OUT_LIST_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (!isNumeric(continueSearchResultJSON.get("code").toString()) || Integer.parseInt(continueSearchResultJSON.get("code").toString()) != 0) {
                    Assert.isTrue(false, "查询出库单列表失败，原因：" + continueSearchResultJSON.get("msg").toString());
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成并存库
                handleStockOutResult(continueSearchResult);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncStockOut() {
        //获取token
        String token = getToken();
        Date lastUpdateTime = stockOutService.searchLastUpdateTime(new StockOutSearchParamPo());
        //查询出库单最后更新时间
        long lastUpdateTimeStamp = 1541575627L;
        //定义分页参数
        Integer offset = 0;
        Integer length = 200;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("search_field_time", "create_time");
        requestBody.put("status", 40);
        if (null != lastUpdateTime) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(lastUpdateTime);
            calendar.add(Calendar.DATE, 1);
            requestBody.put("start_date", new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
        } else {
            requestBody.put("start_date", new SimpleDateFormat("yyyy-MM-dd").format(lastUpdateTimeStamp));
        }
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object stockOutListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, STOCK_OUT_LIST_URL,
                null, requestBody);
        JSONObject stockOutListResult = (JSONObject) stockOutListResultObj;
        if (!isNumeric(stockOutListResult.get("code").toString()) || (Integer.parseInt(stockOutListResult.get("code").toString()) != 0)) {
            Assert.isTrue(false, "查询出库单列表失败，原因：" + stockOutListResult.get("msg").toString());
        }
        JSONArray result = stockOutListResult.getJSONArray("data");
        //防止重复拉取数据，先删数据
        if (Objects.nonNull(result)) {
            lingXingInterfaceMapper.deleteByStartDate(requestBody.get("start_date").toString());
        }
        //转换成并存库
        handleStockOutResult(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) stockOutListResult.get("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", requestBody.get("length"));
                requestBody1.put("search_field_time", requestBody.get("search_field_time"));
                requestBody1.put("start_date", requestBody.get("start_date"));
                requestBody1.put("status", requestBody.get("status"));
                String token1 = getToken();
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token1);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, STOCK_OUT_LIST_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (!isNumeric(continueSearchResultJSON.get("code").toString()) || Integer.parseInt(continueSearchResultJSON.get("code").toString()) != 0) {
                    Assert.isTrue(false, "查询出库单列表失败，原因：" + continueSearchResultJSON.get("msg").toString());
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成并存库
                handleStockOutResult(continueSearchResult);
            }
        }
    }

    private void handleStockInResult(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
        result.forEach(t -> {
            JSONObject stockIn = (JSONObject) t;
            StockInVo stock = new StockInVo();
            stock.setWarehouse(((Integer) stockIn.get("wid")).longValue());
            stock.setReceiptType(stockIn.get("type").toString());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String create_time = sdf.format(stockIn.get("create_time"));
            try {
                stock.setCreateTime(sdf.parse(create_time));
                stock.setLastUpdateTime(stock.getCreateTime());
                stock.setWarehousingDate(sdf.parse(stockIn.get("inbound_time").toString()));
            } catch (ParseException e) {
                Assert.isTrue(false, "日期转换失败");
            }
            stock.setSupplier(((Integer) stockIn.get("supplier_id")).longValue());
            stock.setFreight(new BigDecimal(isNumeric(stockIn.get("return_price").toString()) ? stockIn.get("return_price").toString() : "0.00"));
            stock.setOtherExpenses(new BigDecimal(isNumeric(stockIn.get("other_fee").toString()) ? stockIn.get("other_fee").toString() : "0.00"));
            stock.setCostAllocationType(stockIn.get("fee_part_type").toString());
            stock.setStatus(stockIn.get("status").toString());
            stock.setOrderSn(stockIn.get("order_sn").toString());
            //入库商品
            List<StockInProductItemVo> stockInProductVos = new ArrayList<>();
            JSONArray stockInProducts = stockIn.getJSONArray("item_list");
            if (Objects.nonNull(stockInProducts)) {
                stockInProducts.forEach(s -> {
                    JSONObject stockInProduct = (JSONObject) s;
                    StockInProductItemVo stockInProductVo = new StockInProductItemVo();
                    stockInProductVo.setProductName(stockInProduct.get("product_name").toString());
                    stockInProductVo.setShopName(stockInProduct.get("seller_id").toString());
//					stockInProductVo.setFnsku(stockInProduct.get("fnsku").toString());
                    stockInProductVo.setUnitPrice(new BigDecimal(isNumeric(stockInProduct.get("price").toString()) ? stockInProduct.get("price").toString() : "0.00"));
                    stockInProductVo.setUnitCost(new BigDecimal(isNumeric(stockInProduct.get("single_fee").toString()) ? stockInProduct.get("single_fee").toString() : "0.00"));
                    stockInProductVo.setUnitReceiptCost(new BigDecimal(isNumeric(stockInProduct.get("single_stock_cost").toString()) ? stockInProduct.get("single_stock_cost").toString() : "0.00"));
                    stockInProductVo.setGoodProduct((Integer) stockInProduct.get("product_good_num"));
                    stockInProductVo.setDefectiveProduct((Integer) stockInProduct.get("product_bad_num"));
                    stockInProductVo.setWaitQuantity((Integer) stockInProduct.get("product_qc_num"));
                    stockInProductVo.setQuantity((Integer) stockInProduct.get("product_total"));
                    stockInProductVo.setProductPrice(new BigDecimal(isNumeric(stockInProduct.get("product_amounts").toString()) ? stockInProduct.get("product_amounts").toString() : "0.00"));
                    stockInProductVos.add(stockInProductVo);
                });
            }
            stock.setProductList(stockInProductVos);
            try {
                stockInService.create(stock);
            } catch (Exception e) {
                Assert.isTrue(false, "入库单存入数据库失败");
            }
        });
    }

    private void handleStockOutResult(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
        result.forEach(t -> {
            JSONObject stockOut = (JSONObject) t;
            StockOutVo stockOutVo = new StockOutVo();
            stockOutVo.setOrderSn(stockOut.get("order_sn").toString());
            stockOutVo.setWarehouse(1L);
            stockOutVo.setType(stockOut.get("type").toString());
            stockOutVo.setToWarehouse(1L);
            stockOutVo.setStatus(stockOut.get("status").toString());
            stockOutVo.setDept(1L);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String create_time = stockOut.get("create_time").toString();
            try {
                stockOutVo.setCreateTime(sdf.parse(create_time));
                stockOutVo.setLastUpdateTime(stockOutVo.getCreateTime());
                stockOutVo.setOutTime(sdf.parse(stockOut.get("outbound_time").toString()));
            } catch (ParseException e) {
                Assert.isTrue(false, "日期转换失败");
            }
            List<StockOutProductItemVo> stockOutProductItemVos = new ArrayList<>();
            JSONArray stockOutProducts = stockOut.getJSONArray("item_list");
            if (Objects.nonNull(stockOutProducts)) {
                stockOutProducts.forEach(s -> {
                    JSONObject stockOutProduct = (JSONObject) s;
                    StockOutProductItemVo stockOutProductItemVo = new StockOutProductItemVo();
                    stockOutProductItemVo.setProductName(stockOutProduct.get("product_name").toString());
                    stockOutProductItemVo.setShopName(lingXingInterfaceMapper.getShopNameBySellerId(stockOutProduct.get("seller_id").toString()));
                    stockOutProductItemVo.setFnsku(stockOutProduct.get("fnsku").toString());
                    stockOutProductItemVo.setProductGoodNum((Integer) stockOutProduct.get("product_good_num"));
                    stockOutProductItemVo.setProductBadNum((Integer) stockOutProduct.get("product_bad_num"));
                    stockOutProductItemVo.setPrice(new BigDecimal(isNumeric(stockOutProduct.get("price").toString()) ? stockOutProduct.get("price").toString() : "0.00"));
                    stockOutProductItemVo.setSingleFee(new BigDecimal(isNumeric(stockOutProduct.get("single_fee").toString()) ? stockOutProduct.get("single_fee").toString() : "0.00"));
                    stockOutProductItemVo.setSingleStockCost(new BigDecimal(isNumeric(stockOutProduct.get("single_stock_cost").toString()) ? stockOutProduct.get("single_stock_cost").toString() : "0.00"));
                    stockOutProductItemVo.setProductAmounts(new BigDecimal(isNumeric(stockOutProduct.get("product_amounts").toString()) ? stockOutProduct.get("product_amounts").toString() : "0.00"));
                    stockOutProductItemVo.setFeeCost(new BigDecimal(isNumeric(stockOutProduct.get("fee_cost").toString()) ? stockOutProduct.get("fee_cost").toString() : "0.00"));
                    stockOutProductItemVo.setAmount(new BigDecimal(isNumeric(stockOutProduct.get("amount").toString()) ? stockOutProduct.get("amount").toString() : "0.00"));
                    stockOutProductItemVo.setSku(stockOutProduct.get("sku").toString());
                    stockOutProductItemVo.setQuantity((Integer) stockOutProduct.get("product_total"));
                    stockOutProductItemVos.add(stockOutProductItemVo);
                });
            }
            stockOutVo.setStockOutProducts(stockOutProductItemVos);
            try {
                stockOutService.create(stockOutVo);
            } catch (Exception e) {
                Assert.isTrue(false, "创建出库单失败,原因：" + e.getLocalizedMessage());
            }
        });
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    @Override
    public void syncLocalInventory() {
        //获取token
        String token = getToken();
//		Date lastUpdateTime = stockInService.searchLastUpdateTime(new StockInSearchParamPo());
        //查询出库单最后更新时间
//		long lastUpdateTimeStamp = null != lastUpdateTime?lastUpdateTime.getTime() / 1000:1541575627L;
        //定义分页参数
        Integer offset = 1;
        Integer length = 100;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("start_date", DateUtil.formatDate(new Date()));
        requestBody.put("end_date", DateUtil.formatDate(new Date()));
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, STOCK_LOCAL_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询本地仓期初库存列表失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONArray("data");
        //转换成并存库
        saveInventory(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 2; i <= pageNum; i++) {
//				offset = i * length;
//				requestBody.put("offset", offset);
                //定义查询参数
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", i);
                requestBody1.put("length", length);
                requestBody1.put("start_date", DateUtil.formatDate(new Date()));
                requestBody1.put("end_date", DateUtil.formatDate(new Date()));
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, STOCK_LOCAL_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (inventoryListResult.getInteger("code") != 0) {
                    Assert.isTrue(false, "查询本地仓期初库存列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成并存库
                saveInventory(continueSearchResult);
            }
        }
        log.info(">>>>>>>>>>同步完成");
    }

    private void saveInventory(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
/*        result.forEach(t -> {
            JSONObject object = (JSONObject) t;
            OpeningInventoryVo vo = new OpeningInventoryVo();
            vo.setWid(object.getInteger("sys_wid"));
            vo.setWareHouseName(object.getString("ware_house_name"));
            vo.setSellerName(object.getString("seller_name"));
            vo.setProductName(object.getString("product_name"));
            vo.setProductType(object.getString("product_type"));
            vo.setSku(object.getString("sku"));
            vo.setFnsku(object.getString("fnsku"));
            vo.setAttributeText(object.getString("attribute_text"));
            vo.setStarCount(object.getInteger("day_early_count"));
            vo.setStarCost(object.getBigDecimal("day_early_cost"));
            vo.setWareHouseType("本地仓库");
            try {
                openingInventoryService.create(vo);
            } catch (Exception e) {
//				Assert.isTrue(false, "创建期初库存失败");
                log.error("创建期初库存失败", e);
            }
        });*/
    }

    @Override
    public void syncFbaInventory() {
        //获取token
        String token = getToken();
//		Date lastUpdateTime = stockInService.searchLastUpdateTime(new StockInSearchParamPo());
        //查询出库单最后更新时间
//		long lastUpdateTimeStamp = null != lastUpdateTime?lastUpdateTime.getTime() / 1000:1541575627L;
        String[] sellerIds = shopInfoService.list().stream().map(s -> s.getSellerId()).toArray(String[]::new);
        String sellerIdStr = JSONUtil.toJsonStr(sellerIds);
        //定义分页参数
        Integer offset = 0;
        Integer length = 100;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("start_date", DateUtil.format(new Date(), "yyyy-MM"));
        requestBody.put("end_date", DateUtil.format(new Date(), "yyyy-MM"));
        requestBody.put("seller_id", sellerIdStr);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, STOCK_FBA_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0 || !inventoryListResult.getBoolean("success")) {
            Assert.isTrue(false, "查询FBA仓期初库存列表失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONArray("data");
        //转换成并存库
//		saveFBAInventory(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                //定义查询参数
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("start_date", DateUtil.format(new Date(), "yyyy-MM"));
                requestBody1.put("end_date", DateUtil.format(new Date(), "yyyy-MM"));
                requestBody1.put("seller_id", sellerIds);
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, STOCK_FBA_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (inventoryListResult.getInteger("code") != 0) {
                    Assert.isTrue(false, "查询FBA仓期初库存列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成并存库
//				saveFBAInventory(continueSearchResult);
            }
        }
        log.info(">>>>>>>>>>同步FBA完成");
    }

    @Override
    public void syncShopProfit(JSONObject jsonObject) {
        String startDate;
        String endDate;
        if (Objects.isNull(jsonObject)) {
            startDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            endDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        } else {
            startDate = StringUtils.hasText(jsonObject.getString("startDate")) ? jsonObject.getString("startDate") : new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            endDate = StringUtils.hasText(jsonObject.getString("endDate")) ? jsonObject.getString("endDate") : new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        }
        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer length = 10000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("startDate", startDate);
        requestBody.put("endDate", endDate);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object shopProfitReportResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, SHOP_PROFIT_REPORT_URL,
                null, requestBody);
        JSONObject shopProfitReportResult = (JSONObject) shopProfitReportResultObj;
        if (!isNumeric(shopProfitReportResult.get("code").toString()) || (Integer.parseInt(shopProfitReportResult.get("code").toString()) != 0)) {
            Assert.isTrue(false, "查询出库单列表失败，原因：" + shopProfitReportResult.get("message").toString());
        }
        JSONObject result = (JSONObject) shopProfitReportResult.get("data");
        Integer pages = (Integer) result.get("pages");
        JSONArray finalResult = (JSONArray) result.get("records");
        if (Objects.nonNull(finalResult)) {
            lingXingInterfaceMapper.deleteReportByDate(requestBody.get("startDate").toString(), requestBody.get("endDate").toString());
        }
        //转换成并存库
        handleShopProfitReport(finalResult);
        //判断数据是否取完,若未取完，继续取数据
        if (pages > 1) {
            int pageNum = pages;
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", requestBody.get("length"));
                requestBody1.put("endDate", requestBody.get("endDate"));
                requestBody1.put("startDate", requestBody.get("startDate"));
                String token1 = getToken();
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token1);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, SHOP_PROFIT_REPORT_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (!isNumeric(continueSearchResultJSON.get("code").toString()) || Integer.parseInt(continueSearchResultJSON.get("code").toString()) != 0) {
                    Assert.isTrue(false, "查询出库单列表失败，原因：" + continueSearchResultJSON.get("message").toString());
                }
                JSONObject continueData = (JSONObject) continueSearchResultJSON.get("data");
                JSONArray continueSearchResult = (JSONArray) continueData.get("records");
                //转换成并存库
                handleShopProfitReport(continueSearchResult);
            }
        }
    }

    private void handleShopProfitReport(JSONArray continueSearchResult) {
        if (Objects.isNull(continueSearchResult)) {
            return;
        }
        continueSearchResult.forEach(t -> {
            JSONObject object = (JSONObject) t;
            ShopProfitReportVo shopProfitReportVo = JSONObject.parseObject(object.toJSONString(), ShopProfitReportVo.class);
            List<ShopProfitReportOtherFeeItemVo> otherFeeStr = new ArrayList<>();
            JSONArray otherFeeStr1 = (JSONArray) object.get("otherFeeStr");
            if (Objects.nonNull(otherFeeStr1)) {
                otherFeeStr1.forEach(s -> {
                    ShopProfitReportOtherFeeItemVo shopProfitReportOtherFeeItemVo = JSONObject.parseObject(((JSONObject) s).toJSONString(), ShopProfitReportOtherFeeItemVo.class);
                    otherFeeStr.add(shopProfitReportOtherFeeItemVo);
                });
                shopProfitReportVo.setOtherFeeStr(otherFeeStr);
            }
            try {
                shopProfitReportService.create(shopProfitReportVo);
            } catch (Exception e) {
                Assert.isTrue(false, e.getLocalizedMessage());
            }
        });
    }

    private void saveFBAInventory(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
//        result.forEach(t -> {
//            JSONObject object = (JSONObject) t;
//            OpeningInventoryVo vo = new OpeningInventoryVo();
//            vo.setWid(object.getInteger("wid"));
//            vo.setWareHouseName(object.getString("ware_house_name"));
////			vo.setSellerName(object.getString("seller_name"));
//            vo.setProductName(object.getString("local_name"));
//            vo.setProductType(object.getString("product_type"));
//            vo.setSku(object.getString("local_sku"));
//            vo.setFnsku(object.getString("fnsku"));
//            vo.setAttributeText(object.getString("disposition"));
//            vo.setStarCount(object.getInteger("start_count"));
//            vo.setStarCost(object.getBigDecimal("start_other_amount"));
//            vo.setWareHouseType("FBA仓库");
//            try {
//                openingInventoryService.create(vo);
//            } catch (Exception e) {
////				Assert.isTrue(false, "创建期初库存失败");
//                log.error("创建FBA期初库存失败", e);
//            }
//        });
    }

    @Override
    public void syncSalesOutbound2(JSONObject orderSn) {
        String token = getToken();
        JSONObject object = new JSONObject();
        int pageSize = 50;
        int page = 1;
        object.put("page", page);
        object.put("page_size", pageSize);
        object.put("status_arr", 3);
        String format = LocalDateUtils.format(new Date(), LocalDateUtils.DATE_PATTERN);
//        Calendar cal=Calendar.getInstance();
//        cal.add(Calendar.DATE,-1);
//        Date d=cal.getTime();
//        SimpleDateFormat sp=new SimpleDateFormat("yyyy-MM-dd");
//        String ZUOTIAN=sp.format(d);//获取昨天日期
        object.put("start_date", orderSn.getString("start_Date"));
        object.put("end_date", orderSn.getString("end_Date"));
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, WmsOrderList_URL,
                null, object);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, object, WmsOrderList_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
            }
        }
        addWmsOrderList(inventoryListResult.getJSONArray("data"));
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total");
        for (int i = 1; i < total / 50 + 1; i++) {
            page = page + 1;
            JSONObject object1 = new JSONObject();
            object1.put("page", page);
            object1.put("page_size", pageSize);
            object1.put("status_arr", 3);
//            object1.put("start_date",start_date);
//            object1.put("end_date",end_date);
            //定义URL参数
            Map<String, Object> requestParams1 = new HashMap<>();
            requestParams1.put("access_token", token);
            requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
            requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
            Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    requestParams1, WmsOrderList_URL,
                    null, object1);
            JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
            if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, object1, WmsOrderList_URL);
                if (jsonObject == null) {
                    return;
                }
                if (jsonObject.getInteger("code") == 0) {
                    continueSearchResultJSON = new JSONObject();
                    continueSearchResultJSON = jsonObject;
                } else {
                    Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
                }
            }
            //转换成并存库
            addWmsOrderList(continueSearchResultJSON.getJSONArray("data"));
        }
    }

    @Override
    public void syncSalesOutbound() {
        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer length = 10000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("startDate", DateUtil.formatDate(DateUtil.yesterday()));
        requestBody.put("endDate", DateUtil.formatDate(DateUtil.yesterday()));
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, SALES_OUT_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询销售出库单列表失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONObject("data").getJSONArray("records");
        //转换成并存库
        saveSalesOutbound(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getJSONObject("data").getInteger("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                //定义查询参数
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("startDate", DateUtil.formatDate(DateUtil.yesterday()));
                requestBody1.put("endDate", DateUtil.formatDate(DateUtil.yesterday()));
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, SALES_OUT_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (inventoryListResult.getInteger("code") != 0) {
                    Assert.isTrue(false, "查询销售出库单列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONObject("data").getJSONArray("records");
                //转换成并存库
                saveSalesOutbound(continueSearchResult);
            }
        }
        log.info(">>>>>>>>>>同步完成：" + total);
    }

    public void saveSalesOutbound(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
        for (Object t : result) {
            JSONObject o = (JSONObject) t;
            if (!o.getString("type").equals("Principal")) {
                continue;
            }
            String postedDateStr = o.getString("postedDateLocale").substring(0, 19).replace("T", " ");
            DateTime parse = DateUtil.parse(postedDateStr, "yyyy-MM-dd HH:mm:ss");

            String localSku = o.getString("localSku");
            Product product = productMapper.selectOne(Wrappers.lambdaQuery(Product.class)
                    .select(Product::getId, Product::getSku)
                    .eq(Product::getSku, localSku));
            SalesOutboundVo vo = new SalesOutboundVo();
            vo.setAmazonOrderId(o.getString("amazonOrderId"));
            vo.setSid(o.getLong("sid"));
            vo.setSellerName(o.getString("storeName"));
            vo.setCountryCode(o.getString("countryCode"));
            vo.setAccountType(o.getString("accountType"));
            vo.setFulfillment(o.getString("fulfillment"));
            vo.setEventType(o.getString("eventType"));
            vo.setSellerId(o.getString("sellerId"));
            vo.setSellerSku(o.getString("sellerSku"));
            vo.setType(o.getString("type"));
            vo.setPostedDateLocale(parse);
            vo.setCurrencyCode(o.getString("currencyCode"));
            vo.setCurrencyAmount(o.getBigDecimal("currencyAmount"));
            vo.setQuantity(o.getInteger("quantity"));
            vo.setProcessingStatus(o.getString("processingStatus"));
            vo.setFundTransferStatus(o.getString("fundTransferStatus"));
            vo.setFid(o.getString("fid"));
            vo.setSettlementId(o.getString("settlementId"));
            vo.setLocalSku(o.getString("localSku"));
            vo.setProductId(product == null ? null : product.getId());
            vo.setLocalName(o.getString("localName"));
            vo.setGmtModified(o.getDate("gmtModified"));
            vo.setSourceId(o.getString("id"));
            try {
//				SalesOutbound salesOutbound = salesOutboundService.getOne(Wrappers.lambdaQuery(SalesOutbound.class)
//						.eq(SalesOutbound::getSourceId,o.getString("id")));
                salesOutboundService.create(vo);
//				if(null == salesOutbound){
//				}else{
//					vo.setId(salesOutbound.getId());
//					salesOutboundService.updateById(vo);
//				}
            } catch (Exception e) {
                log.error("创建期初库存失败", e);
            }
        }
    }

    public void updateSalesOutboundOne() {

        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer length = 10000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("startDate", "2023-10-01");
        requestBody.put("endDate", "2023-10-07");
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, SALES_OUT_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询销售出库单列表失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONObject("data").getJSONArray("records");
        //转换成并存库
        saveSalesOutbound(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getJSONObject("data").getInteger("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                //定义查询参数
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("startDate", "2023-10-01");
                requestBody1.put("endDate", "2023-10-07");
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, SALES_OUT_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (inventoryListResult.getInteger("code") != 0) {
                    Assert.isTrue(false, "查询销售出库单列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONObject("data").getJSONArray("records");
                //转换成并存库
                saveSalesOutbound(continueSearchResult);
            }
        }
        log.info(">>>>>>>>>>同步完成：" + total);
    }

    public void updateSalesOutboundTwo() {

        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer length = 10000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("startDate", "2023-10-08");
        requestBody.put("endDate", "2023-10-14");
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, SALES_OUT_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询销售出库单列表失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONObject("data").getJSONArray("records");
        //转换成并存库
        saveSalesOutbound(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getJSONObject("data").getInteger("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                //定义查询参数
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("startDate", "2023-10-08");
                requestBody1.put("endDate", "2023-10-14");
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, SALES_OUT_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (inventoryListResult.getInteger("code") != 0) {
                    Assert.isTrue(false, "查询销售出库单列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONObject("data").getJSONArray("records");
                //转换成并存库
                saveSalesOutbound(continueSearchResult);
            }
        }
        log.info(">>>>>>>>>>同步完成：" + total);
    }

    public void updateSalesOutboundThree() {

        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer length = 10000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("startDate", "2023-10-15");
        requestBody.put("endDate", "2023-10-21");
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, SALES_OUT_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询销售出库单列表失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONObject("data").getJSONArray("records");
        //转换成并存库
        saveSalesOutbound(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getJSONObject("data").getInteger("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                //定义查询参数
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("startDate", "2023-10-15");
                requestBody1.put("endDate", "2023-10-21");
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, SALES_OUT_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (inventoryListResult.getInteger("code") != 0) {
                    Assert.isTrue(false, "查询销售出库单列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                }
                log.info(">>>>>>>>>>当前偏移量：" + offset);
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONObject("data").getJSONArray("records");
                //转换成并存库
                saveSalesOutbound(continueSearchResult);
            }
        }
        log.info(">>>>>>>>>>同步完成：" + total);
    }

    public void updateSalesOutboundFour() {

        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer length = 10000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("startDate", "2023-10-22");
        requestBody.put("endDate", "2023-10-28");
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, SALES_OUT_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询销售出库单列表失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONObject("data").getJSONArray("records");
        //转换成并存库
        saveSalesOutbound(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getJSONObject("data").getInteger("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                //定义查询参数
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("startDate", "2023-10-22");
                requestBody1.put("endDate", "2023-10-28");
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, SALES_OUT_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (inventoryListResult.getInteger("code") != 0) {
                    Assert.isTrue(false, "查询销售出库单列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                }
                log.info(">>>>>>>>>>当前偏移量：" + offset);
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONObject("data").getJSONArray("records");
                //转换成并存库
                saveSalesOutbound(continueSearchResult);
            }
        }
        log.info(">>>>>>>>>>同步完成：" + total);
    }

    public void updateSalesOutbound() {

        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer length = 10000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("startDate", "2023-10-29");
        requestBody.put("endDate", "2023-10-31");
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, SALES_OUT_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询销售出库单列表失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONObject("data").getJSONArray("records");
        //转换成并存库
        saveSalesOutbound(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getJSONObject("data").getInteger("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                //定义查询参数
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("startDate", "2023-10-29");
                requestBody1.put("endDate", "2023-10-31");
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, SALES_OUT_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (inventoryListResult.getInteger("code") != 0) {
                    Assert.isTrue(false, "查询销售出库单列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                }
                log.info(">>>>>>>>>>当前偏移量：" + offset);
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONObject("data").getJSONArray("records");
                //转换成并存库
                saveSalesOutbound(continueSearchResult);
            }
        }
        log.info(">>>>>>>>>>同步完成：" + total);
    }

    @Override
    public void syncPurchaseOrder(Integer offset, Integer length, String startDate, String endDate, Integer isRun) {
        //定义分页参数
        if (length == null) {
            length = 500;
        }
        if (offset == null) {
            offset = 0;
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(startDate)) {
            startDate = DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_FORMAT);
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(endDate)) {
            endDate = DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_FORMAT);
        }
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("start_date", startDate);
        requestBody.put("end_date", endDate);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", getToken());
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, PURCHASEORDERLIST_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        System.out.println(inventoryListResult.getInteger("code") + ".........");
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询采购订单失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONArray("data");
//        for (Object o : result) {
//            JSONObject jsonObject = (JSONObject) o;
//            int status = jsonObject.getIntValue("status");
//            System.out.println(status);
////			int i = 0;
//            if (status == 1) {
////				System.out.println(++i);
//                JSONArray item_list = jsonObject.getJSONArray("item_list");
//                for (Object t : item_list) {
//                    JSONObject jsonObject1 = (JSONObject) t;
//                    String fnsku = jsonObject1.getString("fnsku");
//                    System.out.println(fnsku);
//                }
//            }
////			JSONArray item_list = jsonObject.getJSONArray("item_list");
////			for (Object t:item_list) {
////				JSONObject jsonObject1 = (JSONObject) t;
////				System.out.println(jsonObject1.getString("fnsku"));
////			}
//        }
        savePurchaseOrder(result);
        if (isRun != null && isRun == 1) {
            Integer total = (Integer) inventoryListResult.get("total");
            if (total > length) {
                int pageNum = total / length;
                if (total % length != 0) {
                    pageNum = pageNum + 1;
                }
                for (int i = 1; i < pageNum; i++) {
                    offset = i * length;
                    requestBody.put("offset", offset);
                    //查询列表
                    Object inventoryListResultObj1 = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                            requestParams, PURCHASEORDERLIST_URL,
                            null, requestBody);
                    JSONObject inventoryListResult1 = (JSONObject) inventoryListResultObj1;
                    System.out.println(inventoryListResult1.getInteger("code") + ".........");
                    if (inventoryListResult.getInteger("code") != 0) {
                        Assert.isTrue(false, "查询采购订单失败，原因：" + inventoryListResult1.getString("msg"));
                    }
                    JSONArray result1 = inventoryListResult1.getJSONArray("data");
                    savePurchaseOrder(result);
                }
            }
        }
    }

    @Override
    public void
    syncAmazonOutbound() {
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", 0);
        requestBody.put("length", 1000);
        requestBody.put("start_date", "2023-01-01");
        requestBody.put("end_date", "2023-07-23");
        System.out.println(requestBody);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, OUTBOUNDORDER_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 1) {
            while (inventoryListResult.getInteger("code") != 1) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                token = getToken();
                Map<String, Object> requestParams1 = new HashMap<>();
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", 0);
                requestBody1.put("length", 1000);
                requestBody1.put("start_date", "2023-01-01");
                requestBody1.put("end_date", "2023-07-23");
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, OUTBOUNDORDER_URL,
                        null, requestBody1);
                inventoryListResult = (JSONObject) inventoryListResultObj;
            }
        }
        if (inventoryListResult.getInteger("code") == 1) {
            JSONArray result = inventoryListResult.getJSONObject("data").getJSONArray("records");
            int intValue = inventoryListResult.getJSONObject("data").getIntValue("total");
            System.out.println(intValue + "total");
            List<String> store_ids = new ArrayList<>();
            List<String> seller_fulfillment_order_ids = new ArrayList<>();
            System.out.println(result.size());
            for (Object o : result) {
                JSONObject j = (JSONObject) o;
                String store_id = j.getString("store_id");
                String seller_fulfillment_order_id = j.getString("seller_fulfillment_order_id");
                store_ids.add(store_id);
                seller_fulfillment_order_ids.add(seller_fulfillment_order_id);
            }

            int toIndex = 200;
            for (int i = 0; i < intValue; i = i + 200) {
                if (i + 200 > intValue) {
                    toIndex = intValue - i;
                }
                List<String> newList = new ArrayList<>();
                List<String> newList1 = new ArrayList<>();
                newList = store_ids.subList(i, i + toIndex);
                newList1 = seller_fulfillment_order_ids.subList(i, i + toIndex);
                JSONArray jsonArrayProDate = gosyncAmazonOutboundDetailP(newList, newList1);
                JSONArray jsonArrayLogDate = gosyncAmazonOutboundDetailL(newList, newList1);
                JSONArray jsonArrayReDate = gosyncAmazonOutboundDetailR(newList, newList1);
                saveSonIf(jsonArrayProDate, jsonArrayLogDate, jsonArrayReDate);
                System.out.println("完成");
            }
            saveAmazonOutbound(result);
        }
    }

    private void saveSonIf(JSONArray jsonArrayProDate, JSONArray jsonArrayLogDate, JSONArray jsonArrayReDate) {
//        Connection conn = JdbcUtils.getConnnection();
//        PreparedStatement ps = null;
//        PreparedStatement proSon = null;
//        PreparedStatement logSon1 = null;
//        PreparedStatement logSon2 = null;
//        PreparedStatement logSon3 = null;
//        PreparedStatement logSon4 = null;
//        PreparedStatement reSon1 = null;
//        PreparedStatement reSon2 = null;
//        try {
//            String sqlps = "INSERT INTO outbound_order_detail(id, create_time, remark, phone," +
//                    " scode, store_name, amazon_order_id, seller_fulfillment_order_id," +
//                    " displayable_order_comment, order_status, sales_channel, purchase_date_local, " +
//                    "buyer_name, ship_date, ship_date_utc, speed_category, buyer_email, " +
//                    "address_line1, postal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?," +
//                    " ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
//            String sqlproSon = "INSERT INTO outbound_order_detail_product(id, name, create_time,  msku," +
//                    " quantity, fnsku, sku, item_name, img_url, asin, cancelled_quantity," +
//                    " unfulfillable_quantity, shipped_quantity, parent_outbound_order_detail) " +
//                    "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//            String sqllogSon1 = "INSERT INTO outbound_order_detail_logistics(id,create_time," +
//                    "fulfillment_shipment_status," +
//                    " estimated_arrival_datetime, parent_outbound_order_detail) VALUES (?,?,?,?,?)";
//            String sqllogSon2 = "INSERT INTO outbound_packages_info(id,create_time,package_number, " +
//                    "carrier_code, tracking_number, current_status, estimated_arrival_datetime, " +
//                    "ship_date, parent_outbound_order_detail_logistics) VALUES (?,?,?,?,?,?,?,?,?)";
//            String sqllogSon3 = "INSERT INTO outbound_ship_items(id,create_time,title, quantity," +
//                    " msku, package_number, scode,parent_outbound_packages_info) VALUES (?,?,?,?,?,?,?,?)";
//            String sqllogSon4 = "INSERT INTO outbound_packages_tracking(id,create_time,event_address," +
//                    " country, city, state, event_code, event, event_description, event_date, " +
//                    "parent_outbound_packages_info) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
//            String sqlreSon1 = "INSERT INTO outbound_returntab(id,create_time,scode, order_id, return_date," +
//                    " msku, asin, return_quantity, return_reason, return_status, lpn, customer_comments, " +
//                    "sku,parent_outbound_order_detail) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//            String sqlreSon2 = "INSERT INTO outbound_replacetab(id, name,create_time,replacement_reason," +
//                    " msku, asin_url, shipment_date, parent_outbound_order_detail) " +
//                    "VALUES (?,?,?,?,?,?,?,?)";
//            conn.setAutoCommit(false);
//            ps = conn.prepareStatement(sqlps);
//            proSon = conn.prepareStatement(sqlproSon);
//            logSon1 = conn.prepareStatement(sqllogSon1);
//            logSon2 = conn.prepareStatement(sqllogSon2);
//            logSon3 = conn.prepareStatement(sqllogSon3);
//            logSon4 = conn.prepareStatement(sqllogSon4);
//            reSon1 = conn.prepareStatement(sqlreSon1);
//            reSon2 = conn.prepareStatement(sqlreSon2);
//            if (Objects.isNull(jsonArrayProDate) && Objects.isNull(jsonArrayLogDate) && Objects.isNull(jsonArrayReDate)) {
//                return;
//            }
//            for (int i = 0; i < jsonArrayProDate.size(); i++) {
//                Object pro = jsonArrayProDate.getJSONObject(i);
//                Object log = jsonArrayLogDate.getJSONObject(i);
//                Object re = jsonArrayReDate.getJSONObject(i);
//                JSONObject objectPro = (JSONObject) pro;
//                JSONObject objectLog = (JSONObject) log;
//                JSONObject objectRe = (JSONObject) re;
//                OutboundOrderDetail outboundOrderDetail = new OutboundOrderDetail();
//                Long ID = IdWorker.getId(outboundOrderDetail);
//                ps.setLong(1, ID);
//                ps.setString(2, LocalDateUtils.getTodayNow());
//                ps.setString(3, objectPro.getString("remark"));
//                ps.setString(4, objectPro.getString("phone"));
//                ps.setInt(5, objectPro.getIntValue("sid"));
//                ps.setString(6, objectPro.getString("store_name"));
//                ps.setString(7, objectPro.getString("amazon_order_id"));
//                ps.setString(8, objectPro.getString("seller_fulfillment_order_id"));
//                ps.setString(9, objectPro.getString("displayable_order_comment"));
//                ps.setString(10, objectPro.getString("order_status"));
//                ps.setString(11, objectPro.getString("sales_channel"));
//                ps.setString(12, objectPro.getString("purchase_date_local"));
//                ps.setString(13, objectPro.getString("buyer_name"));
//                ps.setString(14, objectPro.getString("ship_date"));
//                ps.setString(15, objectPro.getString("ship_date_utc"));
//                ps.setString(16, objectPro.getString("speed_category"));
//                ps.setString(17, objectPro.getString("buyer_email"));
//                ps.setString(18, objectPro.getString("address_line1"));
//                ps.setString(19, objectPro.getString("postal_code"));
//                ps.addBatch();
//                JSONArray proInfo = objectPro.getJSONArray("listing_detail_info");
//                for (Object o : proInfo) {
//                    JSONObject proSonObj = (JSONObject) o;
//                    OutboundOrderDetailProduct outboundOrderDetailProduct = new OutboundOrderDetailProduct();
//                    Long proSonID = IdWorker.getId(outboundOrderDetailProduct);
//                    proSon.setLong(1, proSonID);
//                    proSon.setString(2, proSonObj.getString("name"));
//                    proSon.setString(3, LocalDateUtils.getTodayNow());
//                    proSon.setString(4, proSonObj.getString("msku"));
//                    proSon.setInt(5, proSonObj.getIntValue("quantity"));
//                    proSon.setString(6, proSonObj.getString("fnsku"));
//                    proSon.setString(7, proSonObj.getString("local_sku"));
//                    proSon.setString(8, proSonObj.getString("item_name"));
//                    proSon.setString(9, proSonObj.getString("small_image_url"));
//                    proSon.setString(10, proSonObj.getString("asin"));
//                    proSon.setInt(11, proSonObj.getIntValue("cancelled_quantity"));
//                    proSon.setInt(12, proSonObj.getIntValue("unfulfillable_quantity"));
//                    proSon.setInt(13, proSonObj.getIntValue("shipped_quantity"));
//                    proSon.setLong(14, ID);
//                    proSon.addBatch();
//                }
//                JSONArray shipInfo = objectLog.getJSONArray("shipment_info");
//                for (Object o1 : shipInfo) {
//                    JSONObject logSon1Obj = (JSONObject) o1;
//                    OutboundOrderDetailLogistics outboundOrderDetailLogistics = new OutboundOrderDetailLogistics();
//                    long logSon1Id = IdWorker.getId(outboundOrderDetailLogistics);
//                    logSon1.setLong(1, logSon1Id);
//                    logSon1.setString(2, LocalDateUtils.getTodayNow());
//                    logSon1.setString(3, logSon1Obj.getString("fulfillment_shipment_status"));
//                    logSon1.setString(4, logSon1Obj.getString("estimated_arrival_datetime"));
//                    logSon1.setLong(5, ID);
//                    logSon1.addBatch();
//                    JSONArray packages = logSon1Obj.getJSONArray("packages");
//                    for (Object o2 : packages) {
//                        JSONObject logSon2Obj = (JSONObject) o2;
//                        OutboundPackagesInfo outboundPackagesInfo = new OutboundPackagesInfo();
//                        long logSon2Id = IdWorker.getId(outboundPackagesInfo);
//                        logSon2.setLong(1, logSon2Id);
//                        logSon2.setString(2, LocalDateUtils.getTodayNow());
//                        logSon2.setString(3, logSon2Obj.getString("package_number"));
//                        logSon2.setString(4, logSon2Obj.getString("carrier_code"));
//                        logSon2.setString(5, logSon2Obj.getString("tracking_number"));
//                        logSon2.setString(6, logSon2Obj.getString("current_status"));
//                        logSon2.setString(7, logSon2Obj.getString("estimated_arrival_datetime"));
//                        logSon2.setString(8, logSon2Obj.getString("ship_date"));
//                        logSon2.setLong(9, logSon1Id);
//                        logSon2.addBatch();
//                        JSONArray shipItems = logSon2Obj.getJSONArray("shipItems");
//                        for (Object o3 : shipItems) {
//                            JSONObject logSon3Obj = (JSONObject) o3;
//                            OutboundShipItems outboundShipItems = new OutboundShipItems();
//                            long logSon3Id = IdWorker.getId(outboundShipItems);
//                            logSon3.setLong(1, logSon3Id);
//                            logSon3.setString(2, LocalDateUtils.getTodayNow());
//                            logSon3.setString(3, logSon3Obj.getString("title"));
//                            logSon3.setInt(4, logSon3Obj.getIntValue("quantity"));
//                            logSon3.setString(5, logSon3Obj.getString("msku"));
//                            logSon3.setString(6, logSon3Obj.getString("package_number"));
//                            logSon3.setString(7, logSon3Obj.getString("sid"));
//                            logSon3.setLong(8, logSon2Id);
//                            logSon3.addBatch();
//                        }
//                        JSONArray trackingEvents = logSon2Obj.getJSONArray("tracking_events");
//                        for (Object o4 : trackingEvents) {
//                            JSONObject logSon4Obj = (JSONObject) o4;
//                            OutboundPackagesTracking outboundPackagesTracking = new OutboundPackagesTracking();
//                            long logSon4Id = IdWorker.getId(outboundPackagesTracking);
//                            logSon4.setLong(1, logSon4Id);
//                            logSon4.setString(2, LocalDateUtils.getTodayNow());
//                            if ("".equals(logSon4Obj.getString("eventAddress")) || logSon4Obj.getString("eventAddress") == null) {
//                                logSon4.setNull(3, Types.NULL);
//                                logSon4.setNull(4, Types.NULL);
//                                logSon4.setNull(5, Types.NULL);
//                                logSon4.setNull(6, Types.NULL);
//                            } else {
//                                logSon4.setString(3, logSon4Obj.getString("eventAddress"));
//                                logSon4.setString(4, logSon4Obj.getJSONObject("eventAddress").getString("country"));
//                                logSon4.setString(5, logSon4Obj.getJSONObject("eventAddress").getString("city"));
//                                logSon4.setString(6, logSon4Obj.getJSONObject("eventAddress").getString("state"));
//                            }
//                            logSon4.setString(7, logSon4Obj.getString("eventCode"));
//                            logSon4.setString(8, logSon4Obj.getString("event"));
//                            logSon4.setString(9, logSon4Obj.getString("eventDescription"));
//                            logSon4.setString(10, logSon4Obj.getString("eventDate"));
//                            logSon4.setLong(11, logSon2Id);
//                            logSon4.addBatch();
//                        }
//                    }
//                }
//                JSONArray returnTab = objectRe.getJSONObject("order_return_replace_tab").getJSONArray("return_tab");
//                for (Object o5 : returnTab) {
//                    JSONObject reSon1Obj = (JSONObject) o5;
//                    OutboundReturntab outboundReturntab = new OutboundReturntab();
//                    long reSon1Id = IdWorker.getId(outboundReturntab);
//                    reSon1.setLong(1, reSon1Id);
//                    reSon1.setString(2, LocalDateUtils.getTodayNow());
//                    reSon1.setString(3, reSon1Obj.getString("sid"));
//                    reSon1.setString(4, reSon1Obj.getString("order_id"));
//                    reSon1.setString(5, reSon1Obj.getString("return_date"));
//                    reSon1.setString(6, reSon1Obj.getString("msku"));
//                    reSon1.setString(7, reSon1Obj.getString("asin"));
//                    reSon1.setString(8, reSon1Obj.getString("return_quantity"));
//                    reSon1.setString(9, reSon1Obj.getString("return_reason"));
//                    reSon1.setString(10, reSon1Obj.getString("return_status"));
//                    reSon1.setString(11, reSon1Obj.getString("lpn"));
//                    reSon1.setString(12, reSon1Obj.getString("customer_comments"));
//                    reSon1.setString(13, reSon1Obj.getString("local_sku"));
//                    reSon1.setLong(14, ID);
//                    reSon1.addBatch();
//                }
//                JSONArray replaceTab = objectRe.getJSONObject("order_return_replace_tab").getJSONArray("replace_tab");
//                for (Object o6 : replaceTab) {
//                    JSONObject reSon2Obj = (JSONObject) o6;
//                    OutboundReplacetab outboundReplacetab = new OutboundReplacetab();
//                    long reSon2Id = IdWorker.getId(outboundReplacetab);
//                    reSon2.setLong(1, reSon2Id);
//                    reSon2.setString(2, reSon2Obj.getString("name"));
//                    reSon2.setString(3, LocalDateUtils.getTodayNow());
//                    reSon2.setString(4, reSon2Obj.getString("replacement_reason"));
//                    reSon2.setString(5, reSon2Obj.getString("msku"));
//                    reSon2.setString(6, reSon2Obj.getString("asin_url"));
//                    reSon2.setString(7, reSon2Obj.getString("shipment_date"));
//                    reSon2.setLong(8, ID);
//                    reSon2.addBatch();
//                }
//            }
//            ps.executeBatch();
//            proSon.executeBatch();
//            logSon1.executeBatch();
//            logSon2.executeBatch();
//            logSon3.executeBatch();
//            logSon4.executeBatch();
//            reSon1.executeBatch();
//            reSon2.executeBatch();
//            conn.commit();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (ps != null) {
//                    ps.close();
//                }
//                if (proSon != null) {
//                    proSon.close();
//                }
//                if (logSon1 != null) {
//                    logSon1.close();
//                }
//                if (logSon2 != null) {
//                    logSon2.close();
//                }
//                if (logSon3 != null) {
//                    logSon3.close();
//                }
//                if (logSon4 != null) {
//                    logSon4.close();
//                }
//                if (reSon1 != null) {
//                    reSon1.close();
//                }
//                if (reSon2 != null) {
//                    reSon2.close();
//                }
//                if (conn != null) {
//                    conn.close();
//                }
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
////			JdbcUtils.close(conn,ps,psProduct);
//        }
    }

    private JSONArray gosyncAmazonOutboundDetailR(List<String> store_ids, List<String> seller_fulfillment_order_ids) {
        //获取token
        String token = getToken();
        JSONObject param = new JSONObject();
        JSONArray ja = new JSONArray();
        if (store_ids.size() != 0 && seller_fulfillment_order_ids.size() != 0) {
            for (int i = 0; i < store_ids.size(); i++) {
                JSONObject jaobj = new JSONObject();
                jaobj.put("sid", store_ids.get(i));
                jaobj.put("seller_fulfillment_order_id", seller_fulfillment_order_ids.get(i));
                ja.add(jaobj);
            }
        } else {
            return null;
        }
        param.put("order_info", ja);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, returnInformation,
                null, param);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        System.out.println(inventoryListResult.getInteger("code"));
        if (inventoryListResult.getInteger("code") != 0) {
            while (inventoryListResult.getInteger("code") != 0) {
                System.out.println(inventoryListResult.getInteger("code"));
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                token = getToken();
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, returnInformation,
                        null, param);
                inventoryListResult = (JSONObject) inventoryListResultObj;
            }
        }
        JSONArray jsonArray = new JSONArray();
        if (inventoryListResult.getInteger("code") == 0) {
            jsonArray = inventoryListResult.getJSONArray("data");
//			saveAmazonOutboundDetailL(jsonArray);
        }
        return jsonArray;
    }

    private JSONArray gosyncAmazonOutboundDetailL(List<String> store_ids, List<String> seller_fulfillment_order_ids) {
        //获取token
        String token = getToken();
        JSONObject param = new JSONObject();
        JSONArray ja = new JSONArray();
        if (store_ids.size() != 0 && seller_fulfillment_order_ids.size() != 0) {
            for (int i = 0; i < store_ids.size(); i++) {
                JSONObject jaobj = new JSONObject();
                jaobj.put("sid", store_ids.get(i));
                jaobj.put("seller_fulfillment_order_id", seller_fulfillment_order_ids.get(i));
                ja.add(jaobj);
            }
        } else {
            return null;
        }
        param.put("order_info", ja);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, logisticsInformation,
                null, param);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        System.out.println(inventoryListResult.getInteger("code"));
        if (inventoryListResult.getInteger("code") != 0) {
            while (inventoryListResult.getInteger("code") != 0) {
                System.out.println(inventoryListResult.getInteger("code"));
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                token = getToken();
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, logisticsInformation,
                        null, param);
                inventoryListResult = (JSONObject) inventoryListResultObj;
            }
        }
        JSONArray jsonArray = new JSONArray();
        if (inventoryListResult.getInteger("code") == 0) {
            jsonArray = inventoryListResult.getJSONArray("data");
//			saveAmazonOutboundDetailL(jsonArray);
        }
        return jsonArray;
    }

    @Override
    public void syncAfterSaleList() {
        Integer num = 0;
        //获取token
        String token = getToken();
        for (int i = 0; i < 5; i++) {
            JSONArray results = new JSONArray();
            for (int j = 0; j < 30000; j = j + 1000) {
                JSONArray result = null;
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("offset", num);
                requestBody.put("length", 1000);
                requestBody.put("start_date", "2023-01-01");
                requestBody.put("end_date", "2023-07-23");
                Map<String, Object> requestParams = new HashMap<>();
                //定义URL参数
                requestParams.put("access_token", token);
                requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams, AFTERSALELIST_URL,
                        null, requestBody);
                JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
//				System.out.println(inventoryListResult.getInteger("total"));
                if (inventoryListResult.getInteger("code") != 0) {
                    while (inventoryListResult.getInteger("code") != 0) {
                        System.out.println(inventoryListResult.getInteger("code"));
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        token = getToken();
                        Map<String, Object> requestParams1 = new HashMap<>();
                        Map<String, Object> requestBody1 = new HashMap<>();
                        requestBody1.put("offset", num);
                        requestBody1.put("length", 1000);
                        requestBody1.put("start_date", "2023-01-01");
                        requestBody1.put("end_date", "2023-07-23");
                        requestParams1.put("access_token", token);
                        requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                        requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                        inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                                requestParams1, AFTERSALELIST_URL,
                                null, requestBody1);
                        inventoryListResult = (JSONObject) inventoryListResultObj;
                    }
//					System.out.println(inventoryListResult.getInteger("total"));
                }
                if (inventoryListResult.getInteger("code") == 0) {
                    result = inventoryListResult.getJSONArray("data");
                    for (int k = 0; k < result.size(); k++) {
                        JSONObject object = result.getJSONObject(k);
                        results.add(object);
                    }
                    num = num + 1000;
                }
            }
            System.out.println(i + "完成");
//			System.out.println(results);
            saveAfterSaleList(results);
        }
    }

    @Override
    public void syncRoutingOrderList() {
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("sid", "224");
//		requestBody.put("sid","101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,156,159,160,161,162,163,164,165,166,167,168,171,172,173,174,175,176,177,178,180,181,182,185,186,187,188,189,190,191,192,193,194,197,198,199,200,201,202,203,204,205,206,207,208,209,212,213,214,215,216,217,218,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305");
        requestBody.put("page", 1);
        requestBody.put("length", 100);
        requestBody.put("start_time", "2021-02-01 08:13:22");
        requestBody.put("end_time", "2023-07-23 00:00:00");
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, RoutingOrderList_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        Integer total = inventoryListResult.getInteger("total");
        System.out.println(total);
//        saveRoutingOrderList(inventoryListResult.getJSONArray("data"));
    }

    @Override
    public void syncInventoryDetails(int i) {
        Integer length = 400;
        Integer offset = i;
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, InventoryDetails_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getIntValue("code") == 0) {
            System.out.println(inventoryListResult.getIntValue("code") + "======");
            saveInventoryDetails(inventoryListResult.getJSONArray("data"));
        }

//		System.out.println(inventoryListResult.getString("stock_age_list"));
//		JSONArray stock_age_list = inventoryListResult.getJSONArray("stock_age_list");
//		for (Object o: stock_age_list) {
//			JSONObject j = (JSONObject) o;
//			System.out.println(j.getString("name")+".."+j.getString("qty"));
//		}
    }

    private void saveInventoryDetails(JSONArray result) {
        Connection conn = JdbcUtils.getConnnection();
        PreparedStatement ps = null;
        PreparedStatement psProduct1 = null;
        PreparedStatement psProduct2 = null;
        try {
            String sql = "INSERT INTO inventory_detail_orderlist(id,create_time,wcode, sku, scode, " +
                    "fnsku, product_total, product_valid_num, product_bad_num, product_qc_num," +
                    " product_lock_num, stock_cost_total, quantity_receive, stock_cost, " +
                    "product_onway) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            String sqlP1 = "INSERT INTO stockage_info(id, name, create_time," +
                    "qty, parent_inventory_detail_orderlist) VALUES (?,?,?,?,?)";
            String sqlP2 = "INSERT INTO third_inventory_info(id,create_time," +
                    "qty_sellable, qty_pending, qty_reserved, qty_onway, " +
                    "parent_inventory_detail_orderlist) VALUES (?,?,?,?,?,?,?)";
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
            psProduct1 = conn.prepareStatement(sqlP1);
            psProduct2 = conn.prepareStatement(sqlP2);
            if (Objects.isNull(result)) {
                return;
            }
            for (Object o : result) {
                JSONObject object = (JSONObject) o;
                InventoryDetailOrderlist inventoryDetailOrderlist = new InventoryDetailOrderlist();
                long id = IdWorker.getId(inventoryDetailOrderlist);
                ps.setLong(1, id);
                ps.setString(2, LocalDateUtils.getTodayNow());
                ps.setString(3, object.getString("wid"));
                ps.setString(4, object.getString("sku"));
                ps.setString(5, object.getString("seller_id"));
                ps.setString(6, object.getString("fnsku"));
                ps.setInt(7, object.getIntValue("product_total"));
                ps.setInt(8, object.getIntValue("product_valid_num"));
                ps.setInt(9, object.getIntValue("product_bad_num"));
                ps.setInt(10, object.getIntValue("product_qc_num"));
                ps.setInt(11, object.getIntValue("product_lock_num"));
                ps.setBigDecimal(12, object.getBigDecimal("stock_cost_total"));
                ps.setInt(13, object.getIntValue("quantity_receive"));
                ps.setBigDecimal(14, object.getBigDecimal("stock_cost"));
                ps.setInt(15, object.getIntValue("product_onway"));
                ps.addBatch();
                JSONArray stockAgeList = object.getJSONArray("stock_age_list");
                for (Object o1 : stockAgeList) {
                    JSONObject p = (JSONObject) o1;
                    StockageInfoOrder stockageInfoOrder = new StockageInfoOrder();
                    long idp = IdWorker.getId(stockageInfoOrder);
                    psProduct1.setLong(1, idp);
                    psProduct1.setString(2, p.getString("name"));
                    psProduct1.setString(3, LocalDateUtils.getTodayNow());
                    psProduct1.setInt(4, p.getIntValue("qty"));
                    psProduct1.setLong(5, id);
                    psProduct1.addBatch();
                }
                JSONArray thirdInventoryh = object.getJSONArray("third_inventory");
                for (Object o2 : thirdInventoryh) {
                    JSONObject pp = (JSONObject) o2;
                    ThirdInventoryInfo thirdInventoryInfo = new ThirdInventoryInfo();
                    long idpp = IdWorker.getId(thirdInventoryInfo);
                    psProduct2.setLong(1, idpp);
                    psProduct2.setString(2, LocalDateUtils.getTodayNow());
                    psProduct2.setInt(3, pp.getIntValue("qty_sellable"));
                    psProduct2.setInt(4, pp.getIntValue("qty_pending"));
                    psProduct2.setInt(5, pp.getIntValue("qty_reserved"));
                    psProduct2.setInt(6, pp.getIntValue("qty_onway"));
                    psProduct2.setLong(7, id);
                    psProduct2.addBatch();
                }
            }
            ps.executeBatch();
            psProduct1.executeBatch();
            psProduct2.executeBatch();
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (psProduct2 != null) {
                    psProduct2.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JdbcUtils.close(conn, ps, psProduct1);
        }
    }

//    private void saveRoutingOrderList(JSONArray result) {
//        Connection conn = JdbcUtils.getConnnection();
//        PreparedStatement ps = null;
//        try {
//            String sql = "INSERT INTO amzod_routing_order_list(id, create_time, order_number, status, " +
//                    "order_from, country_code, purchase_time, logistics_type_id, logistics_provider_id," +
//                    " platform_list, logistics_type_name, logistics_provider_name, wid, warehouse_name," +
//                    " customer_comment) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//            conn.setAutoCommit(false);
//            ps = conn.prepareStatement(sql);
//            if (Objects.isNull(result)) {
//                return;
//            }
//            for (Object o : result) {
//                JSONObject object = (JSONObject) o;
//                AmzodRoutingOrderList amzodRoutingOrderList = new AmzodRoutingOrderList();
//                long id = IdWorker.getId(amzodRoutingOrderList);
//                ps.setLong(1, id);
//                ps.setString(2, LocalDateUtils.getTodayNow());
//                ps.setString(3, object.getString("order_number"));
//                ps.setString(4, object.getString("status"));
//                ps.setString(5, object.getString("order_from"));
//                ps.setString(6, object.getString("country_code"));
//                ps.setString(7, object.getString("purchase_time"));
//                ps.setString(8, object.getString("logistics_type_id"));
//                ps.setString(9, object.getString("logistics_provider_id"));
//                ps.setString(10, object.getString("platform_list"));
//                ps.setString(11, object.getString("logistics_type_name"));
//                ps.setString(12, object.getString("logistics_provider_name"));
//                ps.setString(13, object.getString("wid"));
//                ps.setString(14, object.getString("warehouse_name"));
//                ps.setString(15, object.getString("customer_comment"));
//                ps.addBatch();
//            }
//            ps.executeBatch();
//            conn.commit();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (ps != null) {
//                    ps.close();
//                }
//                if (conn != null) {
//                    conn.close();
//                }
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
////			JdbcUtils.close(conn,ps,psProduct);
//        }
//    }

    private void saveAfterSaleList(JSONArray result) {
//        Connection conn = JdbcUtils.getConnnection();
//        PreparedStatement ps = null;
//        PreparedStatement psProduct = null;
//        PreparedStatement psProduct1 = null;
//        PreparedStatement psProduct2 = null;
//        try {
//            String sql = "INSERT INTO amzod_after_sale(id,create_time, amazon_order_id, scode, " +
//                    "correlation_id, purchase_time, interval_days, is_mcf_order, seller_country, " +
//                    "delivery_type, order_total_amount, order_total_amount_currency_code, " +
//                    "order_total_amount_number, total_refund_amount, " +
//                    "total_refund_amount_currency_code, total_refund_amount_number, " +
//                    "total_refund_cost, total_refund_cost_currency_code, total_refund_cost_number, " +
//                    "after_type_tag) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//            String sqlP = "INSERT INTO amzod_after_sale_product(id,create_time, sku, small_image_url," +
//                    " item_name, local_name, asin, msku, after_type, after_time, after_interval, " +
//                    "refund_amount, refund_cost, after_quantity, after_reason, return_status, " +
//                    "inventory_attributes, lpn_number, buyers_note, rma_order_number, carriers, " +
//                    "waybill_number, exchange_order_number, md5_new, parent_amzod_after_sale) " +
//                    "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//            String sqlP1 = "INSERT INTO amzod_refund_amount_details(id,create_time,type,amount, " +
//                    "parent_amzod_after_sale_product) VALUES (?,?,?,?,?)";
//            String sqlP2 = "INSERT INTO amzod_refund_cost_details(id,create_time,type,amount, " +
//                    "parent_amzod_after_sale_product) VALUES (?,?,?,?,?)";
//            conn.setAutoCommit(false);
//            ps = conn.prepareStatement(sql);
//            psProduct = conn.prepareStatement(sqlP);
//            psProduct1 = conn.prepareStatement(sqlP1);
//            psProduct2 = conn.prepareStatement(sqlP2);
//            if (Objects.isNull(result)) {
//                return;
//            }
//            for (Object o : result) {
//                JSONObject object = (JSONObject) o;
//                AmzodAfterSale amzodAfterSale = new AmzodAfterSale();
//                long id = IdWorker.getId(amzodAfterSale);
//                ps.setLong(1, id);
//                ps.setString(2, LocalDateUtils.getTodayNow());
//                ps.setString(3, object.getString("amazon_order_id"));
//                ps.setString(4, object.getString("sid"));
//                ps.setString(5, object.getString("correlation_id"));
//                ps.setString(6, object.getString("purchase_time"));
//                ps.setInt(7, object.getIntValue("interval_days"));
//                ps.setString(8, object.getString("is_mcf_order"));
//                ps.setString(9, object.getString("seller_country"));
//                ps.setString(10, object.getString("delivery_type"));
//                ps.setString(11, object.getString("order_total_amount"));
//                ps.setString(12, object.getString("order_total_amount_currency_code"));
//                ps.setString(13, object.getString("order_total_amount_number"));
//                ps.setString(14, object.getString("total_refund_amount"));
//                ps.setString(15, object.getString("total_refund_amount_currency_code"));
//                ps.setString(16, object.getString("total_refund_amount_number"));
//                ps.setString(17, object.getString("total_refund_cost"));
//                ps.setString(18, object.getString("total_refund_cost_currency_code"));
//                ps.setString(19, object.getString("total_refund_cost_number"));
//                ps.setString(20, object.getString("after_type_tag"));
//                ps.addBatch();
//                JSONArray itemList = object.getJSONArray("item_list");
//                for (Object o1 : itemList) {
//                    JSONObject p = (JSONObject) o1;
//                    AmzodAfterSaleProduct amzodAfterSaleProduct = new AmzodAfterSaleProduct();
//                    long idp = IdWorker.getId(amzodAfterSaleProduct);
//                    psProduct.setLong(1, idp);
//                    psProduct.setString(2, LocalDateUtils.getTodayNow());
//                    psProduct.setString(3, p.getString("local_sku"));
//                    psProduct.setString(4, p.getString("small_image_url"));
//                    psProduct.setString(5, p.getString("item_name"));
//                    psProduct.setString(6, p.getString("local_name"));
//                    psProduct.setString(7, p.getString("asin"));
//                    psProduct.setString(8, p.getString("msku"));
//                    psProduct.setString(9, p.getString("after_type"));
//                    psProduct.setString(10, p.getString("after_time"));
//                    psProduct.setString(11, p.getString("after_interval"));
//                    psProduct.setString(12, p.getString("refund_amount"));
//                    psProduct.setString(13, p.getString("refund_cost"));
//                    psProduct.setString(14, p.getString("after_quantity"));
//                    psProduct.setString(15, p.getString("after_reason"));
//                    psProduct.setString(16, p.getString("return_status"));
//                    psProduct.setString(17, p.getString("inventory_attributes"));
//                    psProduct.setString(18, p.getString("lpn_number"));
//                    psProduct.setString(19, p.getString("buyers_note"));
//                    psProduct.setString(20, p.getString("rma_order_number"));
//                    psProduct.setString(21, p.getString("carriers"));
//                    psProduct.setString(22, p.getString("waybill_number"));
//                    psProduct.setString(23, p.getString("exchange_order_number"));
//                    psProduct.setString(24, p.getString("md5_new"));
//                    psProduct.setLong(25, id);
//                    psProduct.addBatch();
//                    JSONArray refundAmount = p.getJSONArray("refund_amount_details");
//                    if (refundAmount != null) {
//                        for (Object o2 : refundAmount) {
//                            JSONObject p1 = (JSONObject) o2;
//                            AmzodRefundAmountDetails amzodRefundAmountDetails = new AmzodRefundAmountDetails();
//                            long idp1 = IdWorker.getId(amzodRefundAmountDetails);
//                            psProduct1.setLong(1, idp1);
//                            psProduct1.setString(2, LocalDateUtils.getTodayNow());
//                            psProduct1.setString(3, p1.getString("type"));
//                            psProduct1.setString(4, p1.getString("amount"));
//                            psProduct1.setLong(5, idp);
//                            psProduct1.addBatch();
//                        }
//                    }
//                    JSONArray refundCost = p.getJSONArray("refund_cost_details");
//                    if (refundCost != null) {
//                        for (Object o3 : refundCost) {
//                            JSONObject p2 = (JSONObject) o3;
//                            AmzodRefundCostDetails amzodRefundCostDetails = new AmzodRefundCostDetails();
//                            long idp2 = IdWorker.getId(amzodRefundCostDetails);
//                            psProduct2.setLong(1, idp2);
//                            psProduct2.setString(2, LocalDateUtils.getTodayNow());
//                            psProduct2.setString(3, p2.getString("type"));
//                            psProduct2.setString(4, p2.getString("amount"));
//                            psProduct2.setLong(5, idp);
//                            psProduct2.addBatch();
//                        }
//                    }
//                }
//            }
//            ps.executeBatch();
//            psProduct.executeBatch();
//            psProduct1.executeBatch();
//            psProduct2.executeBatch();
//            conn.commit();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (psProduct1 != null) {
//                    psProduct1.close();
//                }
//                if (psProduct2 != null) {
//                    psProduct2.close();
//                }
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//            JdbcUtils.close(conn, ps, psProduct);
//        }

    }

    private JSONArray gosyncAmazonOutboundDetailP(List<String> store_ids, List<String> seller_fulfillment_order_ids) {
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap<>();
        JSONObject param = new JSONObject();
        JSONArray ja = new JSONArray();
        if (store_ids.size() != 0 && seller_fulfillment_order_ids.size() != 0) {
            for (int i = 0; i < store_ids.size(); i++) {
                JSONObject jaobj = new JSONObject();
                jaobj.put("sid", store_ids.get(i));
                jaobj.put("seller_fulfillment_order_id", seller_fulfillment_order_ids.get(i));
                ja.add(jaobj);
            }
        } else {
            return null;
        }
        param.put("order_info", ja);
        System.out.println(param);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, productInformation,
                null, param);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        System.out.println(inventoryListResult.getInteger("code"));
        if (inventoryListResult.getInteger("code") != 0) {
            while (inventoryListResult.getInteger("code") != 0) {
                System.out.println(inventoryListResult.getInteger("code"));
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                token = getToken();
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, productInformation,
                        null, param);
                inventoryListResult = (JSONObject) inventoryListResultObj;
            }
        }
        JSONArray jsonArray = new JSONArray();
        if (inventoryListResult.getInteger("code") == 0) {
            jsonArray = inventoryListResult.getJSONArray("data");
        }
        return jsonArray;
    }

    private void saveAmazonOutbound(JSONArray result) {
//        Connection conn = JdbcUtils.getConnnection();
//        PreparedStatement ps = null;
//        PreparedStatement psProduct = null;
//        try {
//            String sql = "INSERT INTO outbound_order(id, create_time, last_update_time, remark, " +
//                    "store_id, store_name, country, amazon_order_id, seller_fulfillment_order_id, " +
//                    "gmt_modified, order_status, purchase_date_local, ship_date, ship_date_utc," +
//                    " buyer_name) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//            String sqlP = "INSERT INTO outbound_order_product(id, name, create_time, " +
//                    "last_update_time, msku, quantity, fnsku, sku, item_name, img_url," +
//                    " asin, parent_outbound_order) VALUES (?, ?,?,?,?,?,?,?,?,?,?,?)";
//            conn.setAutoCommit(false);
//            ps = conn.prepareStatement(sql);
//            psProduct = conn.prepareStatement(sqlP);
//            if (Objects.isNull(result)) {
//                return;
//            }
//            for (Object t : result) {
//                JSONObject jsonObject = (JSONObject) t;
//                OutboundOrder outboundOrder = new OutboundOrder();
//                Long ID = IdWorker.getId(outboundOrder);
//                ps.setLong(1, ID);
//                ps.setString(2, LocalDateUtils.getTodayNow());
//                Date time = jsonObject.getDate("last_update_time");
//                ps.setTimestamp(3, new Timestamp(time.getTime()));
//                ps.setString(4, jsonObject.getString("remark"));
//                ps.setString(5, jsonObject.getString("store_id"));
//                ps.setString(6, jsonObject.getString("store_name"));
//                ps.setString(7, jsonObject.getString("country"));
//                ps.setString(8, jsonObject.getString("amazon_order_id"));
//                ps.setString(9, jsonObject.getString("seller_fulfillment_order_id"));
//                ps.setString(10, jsonObject.getString("gmt_modified"));
//                ps.setString(11, jsonObject.getString("order_status"));
//                ps.setString(12, jsonObject.getString("purchase_date_local"));
//                ps.setString(13, jsonObject.getString("ship_date"));
//                ps.setString(14, jsonObject.getString("ship_date_utc"));
//                ps.setString(15, jsonObject.getString("buyer_name"));
//                ps.addBatch();
//                JSONArray products = jsonObject.getJSONArray("listingInfo");
//                if (Objects.nonNull(products)) {
//                    for (Object s : products) {
//                        JSONObject jsonObject1 = (JSONObject) s;
//                        OutboundOrderProduct outboundOrderProduct = new OutboundOrderProduct();
//                        Long IDP = IdWorker.getId(outboundOrderProduct);
//                        psProduct.setLong(1, IDP);
//                        psProduct.setString(2, jsonObject1.getString("local_name"));
//                        psProduct.setString(3, LocalDateUtils.getTodayNow());
//                        psProduct.setString(4, LocalDateUtils.getTodayNow());
//                        psProduct.setString(5, jsonObject1.getString("msku"));
//                        psProduct.setInt(6, jsonObject1.getIntValue("quantity"));
//                        psProduct.setString(7, jsonObject1.getString("fnsku"));
//                        psProduct.setString(8, jsonObject1.getString("sku"));
//                        psProduct.setString(9, jsonObject1.getString("item_name"));
//                        psProduct.setString(10, jsonObject1.getString("img_url"));
//                        psProduct.setString(11, jsonObject1.getString("asin"));
//                        psProduct.setLong(12, ID);
//                        psProduct.addBatch();
//                    }
//                }
//            }
//            ps.executeBatch();
//            psProduct.executeBatch();
//            conn.commit();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            JdbcUtils.close(conn, ps, psProduct);
//        }
    }

    private void savePurchaseOrder(JSONArray result) {
        Connection conn = JdbcUtils.getConnnection();
        PreparedStatement ps = null;
        PreparedStatement psProduct = null;
        PreparedStatement pshopId = null;
        PreparedStatement pproductId = null;
        PreparedStatement psupplierId = null;
        PreparedStatement pwarehouseId = null;
        PreparedStatement psOrderSn = null;
        PreparedStatement psListing = null;
        try {
            String sql = "INSERT INTO purchase_order(id, purchase_order_code, supplier_id, supplier_code,supplier_name, " +
                    "create_time, last_update_time, last_update_user,wid,wcode,warehouse_name,contact_person,contact_number," +
                    "settlement_method,settlement_describe,payment_method,purchase_currency,shipping_price,other_currency," +
                    "fee_part_type,including_tax,opt_uid,purchaser,remarks,total_price,quantity_received,order_time," +
                    "purchase_quantity,an_status,log_order_sear,arrival_status,pay_status,inspection_type) " +
                    "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

            String sqlP = "INSERT INTO purchase_order_product(id,purchase_order_id,product_id,sku,product_name,del_flag,sid," +
                    "msku,fnsku,application_num,tax_price,tax_rate,amount,quantity_receive,quantity_received," +
                    "quantity_return,expect_arrive_time,plan_sn,scode) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            String sqlShopId = "SELECT id FROM shop_info WHERE del_flag=0 and shop_code=?";
            String sqlProductId = "SELECT id FROM product WHERE del_flag=0 and sku=?";
            String sqlSuppId = "SELECT id FROM `supplier` where del_flag=0 and supplier_code=?";
            String sqlwid = "SELECT id FROM warehouse WHERE del_flag=0 and wid=?";
            String sqlOrderSn = "SELECT 1 FROM purchase_order WHERE purchase_order_code=? and del_flag=0";
            String sqlList = "SELECT id FROM listing_father WHERE fnsku=? and sid=? and sku=? and del_flag=0";
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
            psProduct = conn.prepareStatement(sqlP);
            pshopId = conn.prepareStatement(sqlShopId);
            pproductId = conn.prepareStatement(sqlProductId);
            psupplierId = conn.prepareStatement(sqlSuppId);
            pwarehouseId = conn.prepareStatement(sqlwid);
            psOrderSn = conn.prepareStatement(sqlOrderSn);
            psListing = conn.prepareStatement(sqlList);
            if (Objects.isNull(result)) {
                return;
            }
            for (Object t : result) {
                JSONObject jsonObject = (JSONObject) t;
                psOrderSn.setString(1, jsonObject.getString("order_sn"));
                ResultSet resultSet = psOrderSn.executeQuery();
                int sn = 0;
                while (resultSet.next()) {
                    sn = resultSet.getInt("1");
                }
                if (sn == 1) {
                    continue;
                }
                if (!("1".equals(jsonObject.getString("status")))) {
                    continue;
                }
                PurchaseOrder purchaseOrder = new PurchaseOrder();
                Long ID = IdWorker.getId(purchaseOrder);
                ps.setLong(1, ID);
                ps.setString(2, jsonObject.getString("order_sn"));
                psupplierId.setString(1, jsonObject.getString("supplier_id"));
                ResultSet supRest = psupplierId.executeQuery();
                Long supplier_id = null;
                while (supRest.next()) {
                    supplier_id = supRest.getLong("id");
                }
                if (supplier_id == null) {
                    ps.setNull(3, Types.NULL);
                } else {
                    ps.setLong(3, supplier_id);
                }
                ps.setString(4, jsonObject.getString("supplier_id"));
                ps.setString(5, jsonObject.getString("supplier_name"));
                ps.setString(6, jsonObject.getString("create_time"));
                ps.setString(7, jsonObject.getString("last_time"));
                ps.setString(8, jsonObject.getString("last_uid"));
                pwarehouseId.setString(1, jsonObject.getString("wid"));
                ResultSet widRest = pwarehouseId.executeQuery();
                Long wid = null;
                while (widRest.next()) {
                    wid = widRest.getLong("id");
                }
                if (wid == null) {
                    ps.setNull(9, Types.NULL);
                } else {
                    ps.setLong(9, wid);
                }
                ps.setString(10, jsonObject.getString("wid"));
                ps.setString(11, jsonObject.getString("ware_house_name"));
                ps.setString(12, jsonObject.getString("contact_person"));
                ps.setString(13, jsonObject.getString("contact_number"));
                if ("7".equals(jsonObject.getString("settlement_method"))) {
                    ps.setString(14, "JS01");
                } else {
                    ps.setString(14, "JS02");
                }
                ps.setString(15, jsonObject.getString("settlement_description"));
                if ("1".equals(jsonObject.getString("payment_method"))) {
                    ps.setString(16, "ZF01");
                } else {
                    ps.setString(16, "ZF02");
                }
                ps.setString(17, jsonObject.getString("purchase_currency"));
                ps.setString(18, jsonObject.getString("shipping_price"));
                ps.setString(19, jsonObject.getString("other_fee"));
                ps.setString(20, jsonObject.getString("fee_part_type"));
                ps.setString(21, jsonObject.getString("is_tax"));
                ps.setString(22, jsonObject.getString("opt_uid"));
                ps.setString(23, jsonObject.getString("purchaser_id"));
                ps.setString(24, jsonObject.getString("remark"));
                ps.setString(25, jsonObject.getString("total_price"));
                ps.setInt(26, jsonObject.getInteger("quantity_real") - jsonObject.getInteger("quantity_receive"));
//				SimpleDateFormat bartDateFormat =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date2 = jsonObject.getDate("order_time");
//				java.sql.Date sqlDate = null;
//				try{
//					java.util.Date date = bartDateFormat.parse(dateStringToParse);
//					sqlDate = new java.sql.Date(date.getTime());
//				}
//				catch (Exception ex) {
//					ex.printStackTrace();
//					System.out.println(ex.getMessage());
//				}
                if (jsonObject.getDate("order_time") != null || "".equals(jsonObject.getDate("order_time"))) {
                    ps.setTimestamp(27, new Timestamp(date2.getTime()));
                } else {
                    ps.setNull(27, Types.NULL);
                }
                ps.setString(28, jsonObject.getString("quantity_total"));
                ps.setString(29, jsonObject.getString("status"));
//				System.out.println(jsonObject.getString("logistics_info"));
                ps.setString(30, jsonObject.getString("logistics_info"));
                ps.setString(31, jsonObject.getString("status_shipped"));
                ps.setString(32, jsonObject.getString("pay_status"));
                ps.setString(33, jsonObject.getString("quality_examine_status"));
                ps.addBatch();
                JSONArray jsonArray = jsonObject.getJSONArray("item_list");
                if (Objects.nonNull(jsonArray)) {
                    for (Object s : jsonArray) {
                        JSONObject jsonObject1 = (JSONObject) s;
                        PurchaseOrderProduct purchaseOrderProductr = new PurchaseOrderProduct();
                        Long IDP = IdWorker.getId(purchaseOrderProductr);
                        psProduct.setLong(1, IDP);
                        psProduct.setLong(2, ID);
                        pproductId.setString(1, jsonObject1.getString("sku"));
                        ResultSet pproductIdRest = pproductId.executeQuery();
                        Long pid = null;
                        while (pproductIdRest.next()) {
                            pid = pproductIdRest.getLong("id");
                        }
                        if (pid == null) {
                            psProduct.setNull(3, Types.NULL);
                        } else {
                            psProduct.setLong(3, pid);
                        }
                        psProduct.setString(4, jsonObject1.getString("sku"));
                        psProduct.setString(5, jsonObject1.getString("product_name"));
                        psProduct.setBigDecimal(6, jsonObject1.getBigDecimal("is_delete"));
                        pshopId.setString(1, jsonObject1.getString("sid"));
                        ResultSet pshopIdRest = pshopId.executeQuery();
                        Long sid = null;
                        while (pshopIdRest.next()) {
                            sid = pshopIdRest.getLong("id");
                        }
                        if (sid == null) {
//							sid= Long.valueOf(0);
                            psProduct.setNull(7, Types.NULL);
                        } else {
                            psProduct.setLong(7, sid);
                        }
                        if (jsonObject1.getJSONArray("msku").size() == 0) {
                            psProduct.setString(8, null);
                        } else {
                            psProduct.setString(8, jsonObject1.getJSONArray("msku").getString(0));
                        }
//						psProduct.setString(9,jsonObject1.getString("fnsku"));
                        psProduct.setString(10, jsonObject1.getString("quantity_real"));
                        psProduct.setString(11, jsonObject1.getString("price"));
                        psProduct.setString(12, jsonObject1.getString("tax_rate"));
                        psProduct.setString(13, jsonObject1.getString("amount"));
                        psProduct.setString(14, jsonObject1.getString("quantity_receive"));
                        psProduct.setInt(15, jsonObject1.getInteger("quantity_real") - jsonObject1.getInteger("quantity_receive"));
//						System.out.println(jsonObject1.getString("quantity_return"));
                        psProduct.setString(16, jsonObject1.getString("quantity_return"));
//						System.out.println(jsonObject1.getString("expect_arrive_time"));
//						SimpleDateFormat dateFormat =   new SimpleDateFormat("yyyy-MM-dd");
                        Date date3 = jsonObject1.getDate("expect_arrive_time");
//						java.sql.Date date1 = null;
//						try{
//							java.util.Date date = dateFormat.parse(objectString);
//							date1 = new java.sql.Date(date.getTime());
//						}
//						catch (Exception ex) {
//							ex.printStackTrace();
//							System.out.println(ex.getMessage());
//						}
                        if (jsonObject1.getDate("expect_arrive_time") != null || "".equals(jsonObject1.getDate("expect_arrive_time"))) {
                            psProduct.setDate(17, new java.sql.Date(date3.getTime()));
                        } else {
                            psProduct.setNull(17, Types.NULL);
                        }
                        psProduct.setString(18, jsonObject1.getString("plan_sn"));
                        psProduct.setString(19, jsonObject1.getString("sid"));
                        if ("1".equals(jsonObject1.getString("is_delete"))) {
                            continue;
                        }
                        psListing.setString(1, jsonObject1.getString("fnsku"));
                        psListing.setString(2, jsonObject1.getString("sid"));
                        psListing.setString(3, jsonObject1.getString("sku"));
                        ResultSet resultSet1 = psListing.executeQuery();
                        int i = 0;
                        Long id = null;
                        while (resultSet1.next()) {
                            i++;
                            System.out.println(i);
                            id = resultSet1.getLong("id");
                        }
                        if (id != null) {
                            psProduct.setLong(9, id);
                        } else {
                            //没查到 执行产品详情添加在转换
                            syncProductInfo(jsonObject1.getString("sku"), null);
                            ResultSet resultSetsku = psListing.executeQuery();
                            int iSku = 0;
                            Long idSku = null;
                            while (resultSetsku.next()) {
                                iSku++;
                                System.out.println(iSku);
                                idSku = resultSetsku.getLong("id");
                            }
                            if (idSku != null) {
                                psProduct.setLong(9, idSku);
                            } else {
                                psProduct.setNull(9, Types.NULL);
                            }
                        }
                        psProduct.addBatch();
                    }
                }
            }
            ps.executeBatch();
            psProduct.executeBatch();
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (psupplierId != null) {
                    psupplierId.close();
                }
                if (pwarehouseId != null) {
                    pwarehouseId.close();
                }
                if (pproductId != null) {
                    pwarehouseId.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JdbcUtils.close(conn, ps, psProduct);
        }
    }

    public void updateSalesOutbound(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
        List<SalesOutbound> sales = salesOutboundService.list(Wrappers.lambdaQuery(SalesOutbound.class)
                .eq(SalesOutbound::getLocalSku, ""));

        for (Object t : result) {
            JSONObject o = (JSONObject) t;
            if (!o.getString("type").equals("Principal")) {
                continue;
            }
            String id = o.getString("id");
            List<SalesOutbound> collect = sales.stream().filter(s -> s.getSourceId().equals(id)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect)) {
                continue;
            }
            SalesOutbound salesOutbound = collect.get(0);

            salesOutbound.setLocalSku(o.getString("localSku"));
            salesOutbound.setLocalName(o.getString("localName"));
            salesOutbound.setLastUpdateTime(new Date());

            try {
                salesOutboundService.updateById(salesOutbound);
            } catch (Exception e) {
                log.error("更新失败", e);
            }
        }
    }

    // 期初数据 库存
    @Override
    public void syncInventoryDetails() throws Exception {
        Integer length = 400;
        Integer offset = 0;
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, InventoryDetails_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getIntValue("code") == 0) {
            inventoryListResult = regainLingXingData(inventoryListResult, requestBody, InventoryDetails_URL);
        }
        JSONArray result = inventoryListResult.getJSONArray("data");
        //添加库存
        SaveInventoryList(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) inventoryListResult.get("total");
        if ((total - offset) > length) {
            int pageNum = (total - offset) / length;
            if ((total - offset) % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                int offset1 = (i * length) + offset;
                System.out.println("------------------------------offset----------------------------" + offset1);
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset1);
                requestBody1.put("length", length);
                //查询产品列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, InventoryDetails_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                    continueSearchResultJSON = regainLingXingData(inventoryListResult, requestBody, InventoryDetails_URL);
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成product并入库
                SaveInventoryList(continueSearchResult);
            }
        }
    }

    private void SaveInventoryList(JSONArray result) throws Exception {
        if (Objects.isNull(result)) {
            return;
        }
        List<Inventory> list = new ArrayList<>();
        for (Object t : result) {
            System.out.println("---当前行数据--- " + t.toString());
            JSONObject object1 = (JSONObject) t;
            Inventory inventory = new Inventory();
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(object1.getString("fnsku"))) {
                inventory.setFnSku(object1.getString("fnsku"));
            }
//            object1.getString("仓库名称");
//            object1.getString("sku");
//            object1.getString("seller_id");//店铺id
//
            ShopInfo shopInfo = shopInfoService.getOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getSellerId, object1.getString("seller_id")));
            if (shopInfo == null) {
                throw new Exception(object1.getString("sku") + "没有查到对应店铺");
            }
            inventory.setShopId(shopInfo.getId().toString());
            Warehouse warehouse = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getName, object1.getString("wh_name")));
            if (warehouse == null) {
                throw new Exception(object1.getString("sku") + "没有查到对应仓库");
            }
            inventory.setStockId(warehouse.getId());//仓库

            Product product = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, object1.getString("sku")));
            if (product == null) {
                syncProductInfo(object1.getString("sku"), null);
                product = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, object1.getString("sku")));
                if (product == null) {
                    throw new Exception(object1.getString("sku") + "没有查到对应产品");//
                }
            }
            inventory.setItemId(product.getId());//产品id


            list.add(inventory);
        }
        // inventoryPlacementMapper.in(i)
    }

    // 期初数据 库位
//    @Transactional(rollbackFor = Exception.class)
    @Override
    public void syncInventoryBinDetails() throws Exception {
        Integer length = 10;
        Integer offset = 0;
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询仓位库存明细
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, InventoryBinDetails_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getIntValue("code") != 0) {
            inventoryListResult = regainLingXingData(inventoryListResult, requestBody, InventoryBinDetails_URL);
        }
        JSONArray result = inventoryListResult.getJSONArray("data");
        //添加库位
        SaveInventoryPlacementList(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) inventoryListResult.get("total");
        if ((total - offset) > length) {
            int pageNum = (total - offset) / length;
            if ((total - offset) % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                int offset1 = (i * length) + offset;
                System.out.println("------------------------------offset----------------------------" + offset1);
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset1);
                requestBody1.put("length", length);
                //查询产品列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, InventoryBinDetails_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                    continueSearchResultJSON = regainLingXingData(inventoryListResult, requestBody, InventoryBinDetails_URL);
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成product并入库
                SaveInventoryPlacementList(continueSearchResult);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncInventoryBinDetailsNews() throws Exception {
        //获取数据 处理
        List<JSONObject> list = commonCostingMapper.selectSqlJson("select * from tmp_inventory_open_data  where total!=0  order by product_id  ");
        System.out.println("-----开始处理线程-----");
        Date startData = new Date();
        try {
            ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1, TimeUnit.SECONDS, new LinkedBlockingQueue());
            int listSize = list.size();
            int fetchSize = 1000; //900条执行一IC  in orcale最大查询1000
            for (int i = 0; i < list.size(); i += fetchSize) {
                log.info("-----线程批次" + i + "----");
                try {
                    if (i + fetchSize > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                        fetchSize = listSize - i;
                    }
                    List<JSONObject> newList = list.subList(i, i + fetchSize);

                    executor.submit(() -> {
                        try {
                            //开始-结束copy线程
                            //这里开始
                            List<InventoryPlacement> list1 = new ArrayList<>();
                            List<InventoryStorageVo> inventoryStorageVoList = new ArrayList<>();
                            for (JSONObject map : newList) {
                                //  System.out.println("---当前行数据--- "+t.toString());
                                try {
                                    handleDataNew(inventoryStorageVoList, map);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            Date endDate = new Date();
                            log.info("数据处理完成------------");
                            log.info("用时" + String.valueOf(endDate.getTime() - startData.getTime()));
                            for (InventoryStorageVo inventoryStorageVo : inventoryStorageVoList) {
                                try {
                                    inventoryBusinessService.storageItem(inventoryStorageVo);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log.error("库存入库数据报错" + e.getLocalizedMessage(), inventoryStorageVo != null ? inventoryStorageVo.toString() : null);
                                }
                            }
                            log.info("数据处理完成------------");
                            System.out.println(endDate.getTime() - startData.getTime());
                            Date endDate1 = new Date();
                            log.info("数据入库完成------------");
                            log.info("用时" + String.valueOf(endDate1.getTime() - startData.getTime()));
                            //结束
//                            if(1==1){
//                                throw new Exception("自己抛异常回滚");
//                            }
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    });
                } catch (Exception e) {
                    log.info("线程处理失败 ", e);
                }
            }
            executor.shutdown();
            while (true) {
                if (executor.isTerminated()) {
                    break;
                }
                Thread.sleep(200);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void handleDataNew(List<InventoryStorageVo> inventoryStorageVoList, JSONObject t) throws Exception {
        JSONObject object1 = t;
        InventoryStorageVo inventoryStorageVo = new InventoryStorageVo();
        SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
        inventoryStorageVo.setDocumentType("期初库存");


        if (org.apache.commons.lang3.StringUtils.isNotEmpty(object1.getString("fnsku"))) {
            inventoryStorageVo.setFnSku(object1.getString("fnsku"));
        }
        // 店铺
        inventoryStorageVo.setShopId(object1.getString("shop_info_id"));
        // 仓库id
        inventoryStorageVo.setStockId(object1.getLong("warehouse_id"));//仓库
        inventoryItem.setId(object1.getLong("product_id"));//产品id
        inventoryStorageVo.setItem(inventoryItem);
        //首先获取正常库存 如果 lockNum不是0 新增锁定库存
        inventoryStorageVo.setQty(object1.getBigDecimal("未锁定量")); //lockNum validNum
        //仓位转换
        String whbType = object1.getString("whb_type");//仓位类型	1 待检暂存 2 可用暂存3 次品暂存 4 拣货暂存 5 可用 6 次品  7可用在途  8次品在途 9 上架暂存 暂时放到展示个配置的一致 不用转换
        inventoryStorageVo.setFromBinIdsType(TargetTypeEnum.Normal);
        if ("Inspected".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Inspected);
        } else if ("Storage".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Storage);
        } else if ("RejectLock".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.RejectLock);
        } else if ("Picking".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Picking);
        } else if ("Normal".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Normal);
        } else if ("Defect".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Defect);
        } else if ("Way".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Way);
        } else if ("RejectWay".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.RejectWay);
        } else if ("Display".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Display);
        }
        //入库需要知道类型
        Map<Long, Integer> map = new HashMap<>();
        map.put(object1.getLong("warehouse_bin_id"), object1.getInteger("未锁定量"));
        inventoryStorageVo.setBinIds(map);
        inventoryStorageVoList.add(inventoryStorageVo);
        //如果锁定》0  继续添加锁定量数据
        if (object1.getBigDecimal("锁定量").compareTo(BigDecimal.ZERO) > 0) {
            InventoryStorageVo inventoryStorageVoLock = new InventoryStorageVo();
            BeanUtils.copyProperties(inventoryStorageVo, inventoryStorageVoLock);
            inventoryStorageVoLock.setTo(TargetTypeEnum.Lock);
            inventoryStorageVoLock.setFromBinIdsType(TargetTypeEnum.Lock);
            inventoryStorageVoLock.setQty(object1.getBigDecimal("锁定量"));
            Map<Long, Integer> map1 = new HashMap<>();
            map1.put(object1.getLong("warehouse_bin_id"), object1.getInteger("锁定量"));
            inventoryStorageVoLock.setBinIds(map1);
            inventoryStorageVoList.add(inventoryStorageVoLock);
        }
    }

    @Autowired
    private CommonCostingMapper commonCostingMapper;

    private void thread(List<Map> newList, int i) throws Exception {
        List<InventoryStorageVo> inventoryStorageVoList = new ArrayList<>();
        System.out.println("-----转换" + "线程批次" + i + "----");
        List<ShopInfo> shopInfoList = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class).isNotNull(ShopInfo::getShopCode));
        List<Warehouse> warehouseList = warehouseMapper.selectList(Wrappers.lambdaQuery(Warehouse.class).isNotNull(Warehouse::getWid));
        List<Product> productList = productMapper.selectList(Wrappers.lambdaQuery(Product.class).isNotNull(Product::getSku));
        System.out.println("--------------");
        for (Map map1 : newList) {
            String s1 = JSON.toJSONString(map1);
            JSONObject object1 = JSONObject.parseObject(s1);
            InventoryStorageVo inventoryStorageVo = new InventoryStorageVo();
            SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
            inventoryStorageVo.setDocumentType("期初库存");

            inventoryStorageVo.setItem(inventoryItem);
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(object1.getString("fnsku"))) {
                inventoryStorageVo.setFnSku(object1.getString("fnsku"));
            }

            // 如果是0 没有店铺
            ShopInfo shopInfo = new ShopInfo();
            if (!object1.getString("store_id").equals("0")) {
                // shopInfo = shopInfoService.getOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getShopCode, object1.getString("store_id")));
                shopInfo = shopInfoList.stream().filter(x -> x.getShopCode().equals(object1.getString("store_id"))).findFirst().orElse(null);

//                if (shopInfo == null) {
//                    throw new Exception(object1.getString("sku") + "没有查到对应店铺" + "-对应数据:"+object1.toJSONString() );
//                }

                if (shopInfo == null) {
                    System.out.println(object1.getString("sku") + "没有查到对应店铺" + ":" + object1.toJSONString());
                    log.error(object1.getString("sku") + "没有查到对应店铺" + ":" + object1.toJSONString(), object1.toJSONString());
                    continue;
                    //throw new Exception(object1.getString("sku") + "没有查到对应店铺" + "-对应数据:"+object1.toJSONString());
                }
                inventoryStorageVo.setShopId(shopInfo.getId().toString());
            }

            // 仓库只给了仓库id

            //Warehouse warehouse = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getWid, object1.getString("wid")));
            Warehouse warehouse = warehouseList.stream().filter(x -> x.getWid().equals(object1.getString("wid"))).findFirst().orElse(null);
            if (warehouse == null) {
                System.out.println(object1.getString("sku") + "没有查到对应仓库" + ":" + object1.toJSONString());
                log.error(object1.getString("sku") + "没有查到对应仓库" + ":" + object1.toJSONString(), object1.toJSONString());
                continue;
                //throw new Exception(object1.getString("sku") + "没有查到对应仓库" + "-对应数据:"+object1.toJSONString() );
            }
            inventoryStorageVo.setStockId(warehouse.getId());//仓库

            // Product product = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, object1.getString("sku")));
            Product product = productList.stream().filter(x -> x.getSku().equals(object1.getString("sku"))).findFirst().orElse(null);
            if (product == null) {
                Product products = new ProductVo();
                products.setSku(object1.getString("sku"));
                products.setRemarks("本地自己插入 不做其他处理（初始库存用）");
                productMapper.insert(products);
                //syncProductInfo(object1.getString("sku"), null);
                product = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, object1.getString("sku")));
                if (product == null) {
                    System.out.println(object1.getString("sku") + "没有查到对应产品" + ":" + object1.toJSONString());

                    log.error(object1.getString("sku") + "没有查到对应产品" + ":" + object1.toJSONString(), object1.toJSONString());
                    continue;
                    // throw new Exception(object1.getString("sku") + "没有查到对应产品"+ "-对应数据:"+object1.toJSONString() );//
                }
            }
            inventoryItem.setId(product.getId());//产品id
            inventoryStorageVo.setItem(inventoryItem);
            inventoryStorageVo.setQty(object1.getBigDecimal("total"));

            //仓位转换
            String whbType = object1.getString("whb_type");//仓位类型	1 待检暂存 2 可用暂存3 次品暂存 4 拣货暂存 5 可用 6 次品 个配置的一致 不用转换
            inventoryStorageVo.setFromBinIdsType(TargetTypeEnum.Normal);
            if ("1".equals(whbType)) {
                inventoryStorageVo.setTo(TargetTypeEnum.Inspected);
            } else if ("2".equals(whbType)) {
                inventoryStorageVo.setTo(TargetTypeEnum.Storage);
            } else if ("3".equals(whbType)) {
                inventoryStorageVo.setTo(TargetTypeEnum.RejectLock);
            } else if ("4".equals(whbType)) {
                inventoryStorageVo.setTo(TargetTypeEnum.Picking);
            } else if ("5".equals(whbType)) {
                inventoryStorageVo.setTo(TargetTypeEnum.Normal);
            } else if ("6".equals(whbType)) {
                inventoryStorageVo.setTo(TargetTypeEnum.Defect);
            }
            //入库需要知道类型
            Map<Long, Integer> map = new HashMap<>();
            if (shopInfo.getId() != null) {
                List<WarehouseBinProducts> warehouseBinProductsList = warehouseBinProductsMapper
                        .selectList(Wrappers.lambdaQuery(WarehouseBinProducts.class)
                                .eq(org.apache.commons.lang3.StringUtils.isEmpty(object1.getString("fnsku")), WarehouseBinProducts::getFnskuName, object1.get("fnsku"))
                                .eq(WarehouseBinProducts::getProductId, product.getId())
                                .eq(WarehouseBinProducts::getShopId, shopInfo.getId()));
                if (CollectionUtils.isEmpty(warehouseBinProductsList)) {
                    WarehouseBin warehouseBin = warehouseBinMapper
                            .selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                                    .eq(WarehouseBin::getWarehouseId, warehouse.getId())
                                    .eq(WarehouseBin::getStorageBin, object1.getString("whb_name"))
                                    .eq(WarehouseBin::getType, whbType).last(" limit 1"));
                    if (warehouseBin == null) {
                        System.out.println(object1.getString("sku") + "没有查到对应仓位" + ":" + object1.toJSONString());

                        log.error(object1.getString("sku") + "没有查到对应仓位" + ":" + object1.toJSONString(), object1.toJSONString());
                        continue;
                        //throw new Exception(object1.getString("sku") + "没有查到对应仓位"+ "-对应数据:"+object1.toJSONString() );//
                    }
                    map.put(warehouseBin.getId(), object1.getInteger("total"));
                    inventoryStorageVo.setBinIds(map);
                } else {
                    WarehouseBin warehouseBin = warehouseBinMapper
                            .selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                                    .eq(WarehouseBin::getStorageBin, object1.getString("whb_name"))
                                    .eq(WarehouseBin::getWarehouseId, warehouse.getId())
                                    .in(WarehouseBin::getId, warehouseBinProductsList.stream().map(WarehouseBinProducts::getParentId).collect(Collectors.toList()))
                                    .eq(WarehouseBin::getType, whbType).last(" limit 1"));
                    if (warehouseBin == null) {
                        warehouseBin = warehouseBinMapper
                                .selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                                        .eq(WarehouseBin::getWarehouseId, warehouse.getId())
                                        .eq(WarehouseBin::getStorageBin, object1.getString("whb_name"))
                                        .eq(WarehouseBin::getType, whbType).last(" limit 1"));
                        if (warehouseBin == null) {
                            System.out.println(object1.getString("sku") + "没有查到对应仓位" + ":" + object1.toJSONString());

                            log.error(object1.getString("sku") + "没有查到对应仓位" + ":" + object1.toJSONString(), object1.toJSONString());
                            continue;
                            // throw new Exception(object1.getString("sku") + "没有查到对应仓位"+ "-对应数据:"+object1.toJSONString() );//
//                            log.error(object1.getString("sku") + "没有查到对应仓位" + ":"+object1.toJSONString(),object1.toJSONString());

                        }
                        map.put(warehouseBin.getId(), object1.getInteger("total"));
                        inventoryStorageVo.setBinIds(map);
                    } else {
                        map.put(warehouseBin.getId(), object1.getInteger("total"));
                        inventoryStorageVo.setBinIds(map);
                    }
                }
            } else {
                WarehouseBin warehouseBin = warehouseBinMapper
                        .selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                                .eq(WarehouseBin::getWarehouseId, warehouse.getId())
                                .eq(WarehouseBin::getStorageBin, object1.getString("whb_name"))
                                .eq(WarehouseBin::getType, whbType).last(" limit 1"));
                if (warehouseBin == null) {
                    System.out.println(object1.getString("sku") + "没有查到对应仓位" + ":" + object1.toJSONString());
                    log.error(object1.getString("sku") + "没有查到对应仓位" + ":" + object1.toJSONString(), object1.toJSONString());
                    continue;
                    //throw new Exception(object1.getString("sku") + "没有查到对应仓位"+ "-对应数据:"+object1.toJSONString() );//
//                    log.error(object1.getString("sku") + "没有查到对应仓位" + ":"+object1.toJSONString(),object1.toJSONString());
//                    continue;
                }
                map.put(warehouseBin.getId(), object1.getInteger("total"));
                inventoryStorageVo.setBinIds(map);
            }
            inventoryStorageVoList.add(inventoryStorageVo);
        }
        System.out.println("-----转换完成" + "线程批次" + i + "----");
        for (InventoryStorageVo inventoryStorageVo : inventoryStorageVoList) {
            try {
                inventoryBusinessService.storageItem(inventoryStorageVo);
            } catch (Exception e) {
                log.error("库存入库数据报错" + e.getLocalizedMessage(), inventoryStorageVo != null ? inventoryStorageVo.toString() : null);
            }
        }
        System.out.println("-----入库完成" + "线程批次" + i + "----");
    }

    @Override
    public void testSyncInventoryBinDetails() throws Exception {
        List<Map> list1 = commonCostingMapper.selectSqlMap("SELECT * from inventory_bin_details_data_1695894705 where total!=0   ");


        try {
//            ThreadPoolExecutor executor=new ThreadPoolExecutor(10,10,1,TimeUnit.SECONDS,new LinkedBlockingQueue());
//            int listSize = list1.size();
//            int fetchSize = 10000; //900条执行一
//            for (int i = 0; i < list1.size(); i += fetchSize) {
//                try {
//                    if (i + fetchSize > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
//                        fetchSize = listSize - i;
//                    }
//                    List<Map> newList = list1.subList(i, i + fetchSize);
            int a = 0;
//                   // System.out.println("-----开始处理-----");
//                    executor.submit(()-> {
//                        try {
            this.thread(list1, a);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    });
//                   // System.out.println("-----束用时"+"线程批次"+i+"----");
//                } catch (Exception e) {
//                    log.info("处理失败 ", e);
//                }
//            }
//            executor.shutdown();
//            while (true) {
//                if (executor.isTerminated()) {
//                    break;
//                }
//                Thread.sleep(200);
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(1);
    }

    private void SaveInventoryPlacementList(JSONArray result) throws Exception {
        if (Objects.isNull(result)) {
            return;
        }
        List<InventoryPlacement> list = new ArrayList<>();
        List<InventoryStorageVo> inventoryStorageVoList = new ArrayList<>();
        for (Object t : result) {
            //  System.out.println("---当前行数据--- "+t.toString());
            try {
                handleData(inventoryStorageVoList, (JSONObject) t);
            } catch (Exception e) {
                log.error("库存转换数据报错" + e.getLocalizedMessage(), t != null ? t.toString() : null);
            }
        }
        for (InventoryStorageVo inventoryStorageVo : inventoryStorageVoList) {
            try {
                inventoryBusinessService.storageItem(inventoryStorageVo);
            } catch (Exception e) {
                log.error("库存入库数据报错" + e.getLocalizedMessage(), inventoryStorageVo != null ? inventoryStorageVo.toString() : null);
            }
        }


    }

    private void handleData(List<InventoryStorageVo> inventoryStorageVoList, JSONObject t) throws Exception {
        JSONObject object1 = t;
        InventoryStorageVo inventoryStorageVo = new InventoryStorageVo();
        SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
        inventoryStorageVo.setDocumentType("期初库存");
        inventoryStorageVo.setItem(inventoryItem);

        if (org.apache.commons.lang3.StringUtils.isNotEmpty(object1.getString("fnsku"))) {
            inventoryStorageVo.setFnSku(object1.getString("fnsku"));
        }

        // 如果是0 没有店铺
        ShopInfo shopInfo = new ShopInfo();
        if (!object1.getString("store_id").equals("0")) {
            shopInfo = shopInfoService.getOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getShopCode, object1.getString("store_id")));
//                if (shopInfo == null) {
//                    throw new Exception(object1.getString("sku") + "没有查到对应店铺" + "-对应数据:"+object1.toJSONString() );
//                }

            if (shopInfo == null) {
//                    log.error(object1.getString("sku") + "没有查到对应店铺" + ":"+object1.toJSONString(),object1.toJSONString());
//                    continue;
                throw new Exception(object1.getString("sku") + "没有查到对应店铺" + "-对应数据:" + object1.toJSONString());
            }
            inventoryStorageVo.setShopId(shopInfo.getId().toString());
        }

        // 仓库只给了仓库id
        Warehouse warehouse = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getWid, object1.getString("wid")));
        if (warehouse == null) {
//                log.error(object1.getString("sku") + "没有查到对应仓库" + ":"+object1.toJSONString(),object1.toJSONString());
//                continue;
            throw new Exception(object1.getString("sku") + "没有查到对应仓库" + "-对应数据:" + object1.toJSONString());
        }
        inventoryStorageVo.setStockId(warehouse.getId());//仓库

        Product product = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, object1.getString("sku")));
        if (product == null) {
            syncProductInfo(object1.getString("sku"), null);
            product = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, object1.getString("sku")));
            if (product == null) {
//                    log.error(object1.getString("sku") + "没有查到对应产品" + ":"+object1.toJSONString(),object1.toJSONString());
                throw new Exception(object1.getString("sku") + "没有查到对应产品" + "-对应数据:" + object1.toJSONString());//
            }
        }
        inventoryItem.setId(product.getId());//产品id
        inventoryStorageVo.setItem(inventoryItem);
        inventoryStorageVo.setQty(object1.getBigDecimal("total"));

        //仓位转换
        String whbType = object1.getString("whb_type");//仓位类型	1 待检暂存 2 可用暂存3 次品暂存 4 拣货暂存 5 可用 6 次品 个配置的一致 不用转换
        inventoryStorageVo.setFromBinIdsType(TargetTypeEnum.Normal);
        if ("1".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Inspected);
        } else if ("2".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Storage);
        } else if ("3".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.RejectLock);
        } else if ("4".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Picking);
        } else if ("5".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Normal);
        } else if ("6".equals(whbType)) {
            inventoryStorageVo.setTo(TargetTypeEnum.Defect);
        }
        //入库需要知道类型
        Map<Long, Integer> map = new HashMap<>();
        if (shopInfo.getId() != null) {
            List<WarehouseBinProducts> warehouseBinProductsList = warehouseBinProductsMapper
                    .selectList(Wrappers.lambdaQuery(WarehouseBinProducts.class)
                            .eq(org.apache.commons.lang3.StringUtils.isEmpty(object1.getString("fnsku")), WarehouseBinProducts::getFnskuName, object1.get("fnsku"))
                            .eq(WarehouseBinProducts::getProductId, product.getId())
                            .eq(WarehouseBinProducts::getShopId, shopInfo.getId()));
            if (CollectionUtils.isEmpty(warehouseBinProductsList)) {
                WarehouseBin warehouseBin = warehouseBinMapper
                        .selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                                .eq(WarehouseBin::getStorageBin, object1.getString("whb_name"))
                                .eq(WarehouseBin::getWarehouseId, warehouse.getId())
                                .eq(WarehouseBin::getType, whbType).last(" limit 1"));
                if (warehouseBin == null) {
//                        log.error(object1.getString("sku") + "没有查到对应仓位" + ":"+object1.toJSONString(),object1.toJSONString());
                    throw new Exception(object1.getString("sku") + "没有查到对应仓位" + "-对应数据:" + object1.toJSONString());//
                }
                map.put(warehouseBin.getId(), object1.getInteger("total"));
                inventoryStorageVo.setBinIds(map);
            } else {
                WarehouseBin warehouseBin = warehouseBinMapper
                        .selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                                .eq(WarehouseBin::getStorageBin, object1.getString("whb_name"))
                                .eq(WarehouseBin::getWarehouseId, warehouse.getId())
                                .in(WarehouseBin::getId, warehouseBinProductsList.stream().map(WarehouseBinProducts::getParentId).collect(Collectors.toList()))
                                .eq(WarehouseBin::getType, whbType).last(" limit 1"));
                if (warehouseBin == null) {
                    warehouseBin = warehouseBinMapper
                            .selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                                    .eq(WarehouseBin::getStorageBin, object1.getString("whb_name"))
                                    .eq(WarehouseBin::getWarehouseId, warehouse.getId())
                                    .eq(WarehouseBin::getType, whbType).last(" limit 1"));
                    if (warehouseBin == null) {
                        throw new Exception(object1.getString("sku") + "没有查到对应仓位" + "-对应数据:" + object1.toJSONString());//
//                            log.error(object1.getString("sku") + "没有查到对应仓位" + ":"+object1.toJSONString(),object1.toJSONString());

                    }
                    map.put(warehouseBin.getId(), object1.getInteger("total"));
                    inventoryStorageVo.setBinIds(map);
                } else {
                    map.put(warehouseBin.getId(), object1.getInteger("total"));
                    inventoryStorageVo.setBinIds(map);
                }
            }
        } else {
            WarehouseBin warehouseBin = warehouseBinMapper
                    .selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                            .eq(WarehouseBin::getStorageBin, object1.getString("whb_name"))
                            .eq(WarehouseBin::getWarehouseId, warehouse.getId())
                            .eq(WarehouseBin::getType, whbType).last(" limit 1"));
            if (warehouseBin == null) {
                throw new Exception(object1.getString("sku") + "没有查到对应仓位" + "-对应数据:" + object1.toJSONString());//
//                    log.error(object1.getString("sku") + "没有查到对应仓位" + ":"+object1.toJSONString(),object1.toJSONString());
//                    continue;
            }
            map.put(warehouseBin.getId(), object1.getInteger("total"));
            inventoryStorageVo.setBinIds(map);
        }

        inventoryStorageVoList.add(inventoryStorageVo);
    }

    /**
     * 更新产品
     *
     * @return
     */
    public void updateProduct() {
        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 80000;
        Integer length = 1000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询产品列表
        Object productListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, PRODUCT_LIST_URL,
                null, requestBody);
        JSONObject productListResult = (JSONObject) productListResultObj;
        if (!"0".equals(productListResult.get("code").toString())) {
            Assert.isTrue(false, "查询商品列表失败，原因：" + productListResult.get("msg").toString());
        }
        JSONArray result = productListResult.getJSONArray("data");
        //转换成product并入库
        updateProductResult(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = (Integer) productListResult.get("total");
        if ((total - offset) > length) {
            int pageNum = (total - offset) / length;
            if ((total - offset) % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                int offset1 = (i * length) + offset;
                System.out.println("------------------------------offset----------------------------" + offset1);
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset1);
                requestBody1.put("length", length);
                //查询产品列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, PRODUCT_LIST_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                    Assert.isTrue(false, "查询商品列表失败，原因：" + continueSearchResultJSON.get("msg").toString());
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成product并入库
                updateProductResult(continueSearchResult);
            }
        }
    }

    private void updateProductResult(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
        result.forEach(t -> {
            JSONObject product = (JSONObject) t;
            String sku = product.getString("sku");
            String picUrl = product.getString("pic_url");
            if (org.apache.commons.lang3.StringUtils.isNotBlank(sku) && org.apache.commons.lang3.StringUtils.isNotBlank(picUrl)) {
                Product one = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, sku));
                if (null != one && one.getPicUrl() == null) {
                    ProductVo model = new ProductVo();
                    BeanUtils.copyProperties(one, model);
                    model.setPicUrl(updateUrl(sku, picUrl));
                    try {
                        productService.update(model);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public List<SysFile> updateUrl(String sku, String picUrl) {
        try {
//			InputStream inputStream = new URL(picUrl).openStream();
//			int potIndex = picUrl.lastIndexOf(".");
            File file = new File(download(picUrl, sku));
            FileInputStream input = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "image/jpeg", IOUtils.toByteArray(input));
            List<SysFile> list = new ArrayList();
            list.add(fileService.upload(multipartFile, null));
            return list;
        } catch (Exception e) {
            log.error("上传图片异常", e);
            return null;
        }

    }

    public String download(String urlString, String imgName) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        int potIndex = urlString.lastIndexOf(".");
        String filename = "E:\\product\\" + imgName + urlString.substring(potIndex);  //本地路径及图片名称
        File file = new File(filename);
        FileOutputStream os = new FileOutputStream(file, true);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        System.out.println(imgName);
        // 完毕，关闭所有链接
        os.close();
        is.close();

        return filename;
    }

    @Override
    public void syncInboundShipmentList() throws Exception {
        RedissonClient redissonClient = SpringUtil.getBean(RedissonClient.class);
        RLock lock = redissonClient.getLock("send_goods");
        org.springframework.util.Assert.isTrue(!lock.isLocked(), "正在同步数据");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String todayNow = LocalDateUtils.getTodayNow();
                try {
                    Boolean tryLock = lock.tryLock(1, 1800, TimeUnit.SECONDS);
                    org.springframework.util.Assert.isTrue(tryLock, "正在同步数据");
                    executionMethod();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    org.springframework.util.Assert.isTrue(false, "正在同步数据");
                } catch (Exception e) {
                    log.error("发货单拉取:" + todayNow, e.getLocalizedMessage());
                } finally {
                    if (lock.isLocked()) {
                        lock.unlock();
                    }
                }
            }
        }).start();
    }

    public void executionMethod() throws Exception {
        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer length = 20;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("status", 0);//待发货
        // requestBody.put("startDate", DateUtil.formatDate(DateUtil.yesterday()));
        //  requestBody.put("endDate", DateUtil.formatDate(DateUtil.yesterday()));
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询销FBA发货单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, InboundShipmentList_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询销FBA发货单列表失败，原因：" + inventoryListResult.getString("msg"));
        } else {
            log.info("---- begin ----");
        }
        JSONArray result = inventoryListResult.getJSONObject("data").getJSONArray("list");
        //查询仓库的
        QueryWrapper<Warehouse> queryWrapper2 = new QueryWrapper();
        queryWrapper2.select("id,name");
        List<Warehouse> list2 = warehouseService.list(queryWrapper2);

        //加载所有的店铺
        QueryWrapper<ShopInfo> queryWrapper4 = new QueryWrapper();
        queryWrapper4.select("id,shop_name");
        List<ShopInfo> list4 = shopInfoService.list(queryWrapper4);
        //转换成并存库
        saveFBAInvoice(result, token, list2, list4);

        Long beginTime = System.currentTimeMillis();
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getJSONObject("data").getInteger("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                //定义查询参数
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody.put("status", 1);
                // requestBody.put("startDate", DateUtil.formatDate(DateUtil.yesterday()));
                //  requestBody.put("endDate", DateUtil.formatDate(DateUtil.yesterday()));
                String token1 = getToken();
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token1);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询销FBA发货单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, InboundShipmentList_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (inventoryListResult.getInteger("code") != 0) {
//                    Assert.isTrue(false, "查询销FBA发货单列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                    log.error("查询销FBA发货单列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                    continue;
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONObject("data").getJSONArray("list");
                //转换成并存库
                saveFBAInvoice(continueSearchResult, token1, list2, list4);
                log.info("processed " + String.valueOf(i) + "/" + String.valueOf(pageNum) + ", 用时 " + String.valueOf((System.currentTimeMillis() - beginTime) / 1000.0000) + " sec.");
            }
        }
        log.info(">>>>>>>>>>FBA发货单同步完成：" + total);
    }

    @Transactional(rollbackFor = Exception.class)
    public void executionMethod2() throws Exception {
        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer length = 20;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("status", 0);//待发货
        // requestBody.put("startDate", DateUtil.formatDate(DateUtil.yesterday()));
        //  requestBody.put("endDate", DateUtil.formatDate(DateUtil.yesterday()));
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询销FBA发货单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, InboundShipmentList_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询销FBA发货单列表失败，原因：" + inventoryListResult.getString("msg"));
        } else {
            log.info("---- begin ----");
        }
        JSONArray result = inventoryListResult.getJSONObject("data").getJSONArray("list");
        //查询仓库的
        QueryWrapper<Warehouse> queryWrapper2 = new QueryWrapper();
        queryWrapper2.select("id,name");
        List<Warehouse> list2 = warehouseService.list(queryWrapper2);

        //加载所有的店铺
        QueryWrapper<ShopInfo> queryWrapper4 = new QueryWrapper();
        queryWrapper4.select("id,shop_name");
        List<ShopInfo> list4 = shopInfoService.list(queryWrapper4);
        //转换成并存库
        saveFBAInvoice2(result, token, list2, list4);

        Long beginTime = System.currentTimeMillis();
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getJSONObject("data").getInteger("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                //定义查询参数
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("status", 0);
                // requestBody.put("startDate", DateUtil.formatDate(DateUtil.yesterday()));
                //  requestBody.put("endDate", DateUtil.formatDate(DateUtil.yesterday()));
                String token1 = getToken();
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token1);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询销FBA发货单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, InboundShipmentList_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (inventoryListResult.getInteger("code") != 0) {
//                    Assert.isTrue(false, "查询销FBA发货单列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                    log.error("查询销FBA发货单列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                    continue;
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONObject("data").getJSONArray("list");
                //转换成并存库
                saveFBAInvoice2(continueSearchResult, token1, list2, list4);
                log.info("processed " + String.valueOf(i) + "/" + String.valueOf(pageNum) + ", 用时 " + String.valueOf((System.currentTimeMillis() - beginTime) / 1000.0000) + " sec.");
            }
        }
        log.info(">>>>>>>>>>FBA发货单同步完成：" + total);
    }

    private void saveFBAInvoice2(JSONArray result, String token, List<Warehouse> list2, List<ShopInfo> list4) throws Exception {
        if (Objects.isNull(result)) {
            return;
        }
        log.info("JSONArray size is " + String.valueOf(result.size()));

        JSONArray jsonArray = new JSONArray();
        Map<String, Object> hashMap = new HashMap<>();
        for (Object t : result) {
            JSONObject o = (JSONObject) t;
            hashMap.put((String) o.get("shipment_sn"), o.get("relate_list"));
            jsonArray.add(o.get("shipment_sn"));
        }
        //String token = getToken();
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("shipment_sn_arr", jsonArray);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", getToken());
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询销FBA发货单列表详情 批量
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, InboundShipmentListMwsDetailList_URL,
                null, requestBody);
//        System.out.println(JSON.toJSONString(inventoryListResultObj));
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
//            Assert.isTrue(false, "查询销FBA发货单列表详情失败，原因：" + inventoryListResult.getString("msg"));
            log.error("查询销FBA发货单列表详情失败，原因：" + inventoryListResult);
            return;
        }
        JSONArray list = inventoryListResult.getJSONArray("data");
        List<FBAInvoiceVo> fbaInvoiceVoList = new ArrayList<>();

//        JSONArray relate_list = (JSONArray) inventoryListResult.get("relate_list");
//        if(true){
//            return;
//        }
        Set<String> collect7 = new HashSet<>();
        for (Object o : list) {
            JSONObject object = (JSONObject) o;
            JSONArray items = object.getJSONArray("items");
            for (Object o1 : items) {
                JSONObject object1 = (JSONObject) o1;
                collect7.add(object1.getString("sku"));
            }
        }
        //查询所有的产品信息
        QueryWrapper<Product> queryWrapper3 = new QueryWrapper();
        queryWrapper3.select("id,sku,pic_url");
        queryWrapper3.in("sku", collect7);
        List<Product> list3 = productService.list(queryWrapper3);

        for (Object o : list) {
            JSONObject object = (JSONObject) o;
            FBAInvoiceVo fbaInvoiceVo = new FBAInvoiceVo();
            fbaInvoiceVo.setInoviceCode(object.getString("shipment_sn"));
            List<String> shipCode = new ArrayList<String>();
            if (hashMap.get(object.getString("shipment_sn")) != null) {
                JSONArray shipment_sn1 = (JSONArray) hashMap.get(object.getString("shipment_sn"));
                for (Object o1 : shipment_sn1) {
                    JSONObject object2 = (JSONObject) o1;
                    if (!shipCode.contains(object2.get("shipment_id"))) {
                        shipCode.add((String) object2.get("shipment_id"));
                    }
                }
            }
            fbaInvoiceVo.setShipmentCode(shipCode.size() > 0 ? shipCode.get(0) : null);
//            Warehouse warehouse1 = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getName, object.getString("wname")));
            Warehouse warehouse1 = list2.stream().filter(x -> x.getName().equals(object.getString("wname"))).findFirst().get();
            if (warehouse1 == null) {
//                throw new Exception(object.getString("wname") + "没有查到对应仓库");
                log.error(object.getString("wname") + "没有查到对应仓库");
                return;
            }
            fbaInvoiceVo.setDeliveryWarehouse(warehouse1.getId());
            fbaInvoiceVo.setTransportMode(object.getString("logistics_list_type"));
            fbaInvoiceVo.setLogisticsProvider(object.getString("logistics_provider_name"));
            fbaInvoiceVo.setLogisticsChannel(object.getString("logistics_channel_name"));
            fbaInvoiceVo.setLxCreateUser(object.getString("create_user"));
            fbaInvoiceVo.setCreateTime(LocalDateUtils.toDate(object.getString("gmt_create"), LocalDateUtils.DATE_TIME_PATTERN));
            //islockinventory
            fbaInvoiceVo.setIslockinventory("0");
            fbaInvoiceVo.setCreateUser(1L);
            JSONArray logistics = object.getJSONArray("logistics");
            if (logistics.size() > 0) {
                JSONObject logistics1 = (JSONObject) logistics.get(0);
                fbaInvoiceVo.setLogisticsTrackingNumber(logistics1.getString("tracking_number"));
            }
            fbaInvoiceVo.setLogisticsInfo(org.apache.commons.lang3.StringUtils.join(object.getJSONObject("head_logistics_list").getJSONArray("track_list"), ","));

            fbaInvoiceVo.setSendName(object.getString("shipment_user"));
            fbaInvoiceVo.setSendTime(object.getDate("shipment_time"));
            fbaInvoiceVo.setExpectReachTime(object.getDate("expected_arrival_date"));
            fbaInvoiceVo.setRealitySendTime(object.getDate("actual_shipment_time"));
            fbaInvoiceVo.setLogisticsCenterCode(object.getString("destination_fulfillment_center_id"));
            fbaInvoiceVo.setPaymentStatus(object.getString("pay_status"));
            fbaInvoiceVo.setInvoiceStatus("30");
            //gmt_create   object.getString("gmt_create")
//            fbaInvoiceVo.setCreateTime(object.getDate("gmt_create"));
            fbaInvoiceVo.setPrintNum(object.getIntValue("print_num"));
            if (fbaInvoiceVo.getPrintNum() != null && fbaInvoiceVo.getPrintNum() > 0) {
                fbaInvoiceVo.setPrintStatus("1");
            } else {
                fbaInvoiceVo.setPrintStatus("0");
            }
            fbaInvoiceVo.setPickTime(object.getDate("pick_time"));
//            fbaInvoiceVo.setLxCreateUser(object.getString("create_user")); //创建人
//            fbaInvoiceVo.setCreateTime(object.getDate("gmt_create"));
            fbaInvoiceVo.setIsPick(object.getString("is_pick"));


            // fbaInvoiceVo.setShipmentPlanTime(object.getDate("shipment_time"));// 计划发货时间 无
            fbaInvoiceVo.setLogisticsStatus(object.getString("order_logistics_status"));
            // fbaInvoiceVo.seVat(object.getString("shipment_time"));  //税号？
            //物流预计时效
            //fbaInvoiceVo.setAllocationType(object.getString("aux_head_fee_type"));分摊类型？
            fbaInvoiceVo.setRemark(object.getString("remark"));
            // fbaInvoiceVo.setPrincipal(object.getString("shipment_time"));  //负责人 无
            JSONArray fileList = object.getJSONArray("fileList");
            fbaInvoiceVo.setFile(org.apache.commons.lang3.StringUtils.join(fileList, ","));  //fileList
            //object.getString("sname"); //获取店铺名称查询对应店铺
            //items 文档上是商品
            JSONArray items = object.getJSONArray("items");
            List<FBAInvoiceDetailItemVo> invoiceDetailList = new ArrayList<>();
            for (Object o1 : items) {
                FBAInvoiceDetailItemVo fbaInvoiceDetailItemVo = new FBAInvoiceDetailItemVo();
                JSONObject object1 = (JSONObject) o1;

//                ShopInfo shopInfo = shopInfoService.getOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getShopName, object1.getString("sname")));
                //list4
                System.out.println(object1.getString("sname"));
                ShopInfo shopInfo = list4.stream().filter(x -> x.getShopName().equals(object1.getString("sname"))).findFirst().orElse(null);
                if (shopInfo == null) {
                    throw new Exception(object1.getString("sname") + "没有查到对应店铺");
                }
                fbaInvoiceDetailItemVo.setShopId(shopInfo.getId());//店铺object1.getLong("sid")

//                Warehouse warehouse = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getName, object1.getString("wname")));
                Warehouse warehouse = list2.stream().filter(x -> x.getName().equals(object.getString("wname"))).findFirst().orElse(null);
                if (warehouse == null) {
                    throw new Exception(object1.getString("wname") + "没有查到对应仓库");
                }
                fbaInvoiceDetailItemVo.setWarehouse(warehouse.getId());//仓库

//                Product product = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, object1.getString("sku")));
                Product product = list3.stream().filter(x -> x.getSku().equals(object1.getString("sku"))).findFirst().orElse(null);
                if (product == null) {
                    throw new Exception(object1.getString("sku") + "没有查到对应产品");
                }
                //listingFatherServiceImpl
                fbaInvoiceDetailItemVo.setName(product.getId());//产品id
                fbaInvoiceDetailItemVo.setMsku(object1.getString("msku"));
                if (!ObjectUtils.isEmpty(object1.getString("fulfillment_network_sku"))) {
                    fbaInvoiceDetailItemVo.setFnsku(object1.getString("fulfillment_network_sku"));
                }
                //fbaInvoiceDetailItemVo.setName(object1.getLong("product_id"));//待转
                fbaInvoiceDetailItemVo.setSku(object1.getString("sku"));
                fbaInvoiceDetailItemVo.setCountry(object1.getString("nation")); //国家
                fbaInvoiceDetailItemVo.setPlanShipCode(object1.getString("isp_id")); //计划id 转换？
                // 货件单号 ？
                fbaInvoiceDetailItemVo.setPicUrl(product.getPicUrl());
                fbaInvoiceDetailItemVo.setPackageLength(object1.getBigDecimal("cg_package_length"));//包装规格长
                fbaInvoiceDetailItemVo.setPackageWidth(object1.getBigDecimal("cg_package_width"));
                fbaInvoiceDetailItemVo.setPackageHeight(object1.getBigDecimal("cg_package_height"));
                fbaInvoiceDetailItemVo.setOneSuttle(object1.getBigDecimal("cg_box_net_weight"));// 单箱净重
                fbaInvoiceDetailItemVo.setOneGross(object1.getBigDecimal("cg_product_gross_weight"));// 商品毛重（
                fbaInvoiceDetailItemVo.setTotalSuttle(object1.getBigDecimal("total_nw"));//总净重（G）
                fbaInvoiceDetailItemVo.setTotalGross(object1.getBigDecimal("total_gw"));//总毛重（G）
                fbaInvoiceDetailItemVo.setPlanSendQuantity(object1.getIntValue("shipment_plan_quantity"));//计划发货量
                fbaInvoiceDetailItemVo.setAsin(object1.getString("asin"));
                fbaInvoiceDetailItemVo.setParentAsin(object1.getString("parent_asin"));
                fbaInvoiceDetailItemVo.setDeclarationQuantity(object1.getIntValue("apply_num"));//申报量
                fbaInvoiceDetailItemVo.setTaxAmount(object1.getBigDecimal("tax_amount"));//税费
                fbaInvoiceDetailItemVo.setSendQuantity(object1.getIntValue("num"));//发货数量
                // fbaInvoiceDetailItemVo.setShipmentShop(object1.getString("sname"));//发货仓库店铺
                //object1.getString("seller_name")shipmentShop

                if (object1.getString("seller_name") != null && !object1.getString("seller_name").equals("")) {
                    ShopInfo sellerName = shopInfoService.getOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getShopName, object1.getString("seller_name")));
                    if (sellerName == null) {
                        throw new Exception(object1.getString("seller_name") + "没有查到对应发货店铺");
                    }
                    fbaInvoiceDetailItemVo.setShipmentShop(sellerName.getId());//发货仓库店铺
                } else {

                }
                fbaInvoiceDetailItemVo.setShipmentCode(object1.getString("shipment_id"));//shipment_id
                //发货的fnsku
                if (object1.getString("fnsku") != null && !object1.getString("fnsku").equals("")) {
                    fbaInvoiceDetailItemVo.setShipmentShopFnsku(object1.getString("fnsku"));
                }
                //发货仓库FUSKU
                // fbaInvoiceDetailItemVo.setWarehouseBin(object1.getLong(""));//仓位(数量)??
                //   fbaInvoiceDetailItemVo.setPicUrl(object1.getString("pic_url"));//图片URL
                JSONArray whbCodeList = object1.getJSONArray("whb_code_list");
                if (whbCodeList != null && whbCodeList.size() > 0) {
                    JSONObject whbCode = (JSONObject) whbCodeList.get(0);
                    fbaInvoiceDetailItemVo.setWhbCode(whbCode.getString("whb_code"));//仓位编码
                    //查询仓位
                    WarehouseBin whbCode1 = warehouseBinService.getOne(Wrappers.lambdaQuery(WarehouseBin.class)
                            .eq(WarehouseBin::getStorageBin, whbCode.getString("whb_code")));
                    if (whbCode1 != null) {
                        //outBingId
                        fbaInvoiceDetailItemVo.setWarehouseBin(whbCode1.getId());
                        fbaInvoiceDetailItemVo.setOutBingId(whbCode1.getId());
                    } else {
                        //查不到找可用库存
                        whbCode1 = warehouseBinService.getOne(Wrappers.lambdaQuery(WarehouseBin.class)
                                .eq(WarehouseBin::getStorageBin, whbCode.getString("whb_code_name"))
                                .eq(WarehouseBin::getWarehouseId, warehouse.getId()));
                        if (whbCode1 == null) {
                            throw new Exception(whbCode.getString("whb_code") + "仓位编码不存在");
                        } else {
                            fbaInvoiceDetailItemVo.setWhbCode(whbCode.getString("whb_code_name"));//仓位编码
                            fbaInvoiceDetailItemVo.setWarehouseBin(whbCode1.getId());
                            fbaInvoiceDetailItemVo.setOutBingId(whbCode1.getId());
                        }
                    }
                }
                invoiceDetailList.add(fbaInvoiceDetailItemVo);
            }
            fbaInvoiceVo.setInvoiceDetailList(invoiceDetailList);
            fbaInvoiceVoList.add(fbaInvoiceVo);
        }
        for (FBAInvoiceVo fbaInvoiceVo : fbaInvoiceVoList) {
            try {
                FBAInvoice one = fbaInvoiceMapper.selectOne(Wrappers.lambdaQuery(FBAInvoice.class).eq(FBAInvoice::getInoviceCode, fbaInvoiceVo.getInoviceCode()));
                if (one != null) {
                    fbaInvoiceVo.setId(one.getId());
//                    fbaInvoiceService.update(fbaInvoiceVo);
                } else {
                    fbaInvoiceService.create(fbaInvoiceVo);
                }
//                fbaInvoiceService.shipping(Arrays.asList(fbaInvoiceVo.getId()));
            } catch (Exception e) {
                log.error("FBA发货单同步添加失败", e);
            }
        }
    }


    private void saveFBAInvoice(JSONArray result, String token, List<Warehouse> list2, List<ShopInfo> list4) throws Exception {
        if (Objects.isNull(result)) {
            return;
        }
        log.info("JSONArray size is " + String.valueOf(result.size()));

        JSONArray jsonArray = new JSONArray();
        Map<String, Object> hashMap = new HashMap<>();
        for (Object t : result) {
            JSONObject o = (JSONObject) t;
            hashMap.put((String) o.get("shipment_sn"), o.get("relate_list"));
            jsonArray.add(o.get("shipment_sn"));
        }
        //String token = getToken();
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("shipment_sn_arr", jsonArray);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", getToken());
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询销FBA发货单列表详情 批量
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, InboundShipmentListMwsDetailList_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
//            Assert.isTrue(false, "查询销FBA发货单列表详情失败，原因：" + inventoryListResult.getString("msg"));
            log.error("查询销FBA发货单列表详情失败，原因：" + inventoryListResult);
            return;
        }
        JSONArray list = inventoryListResult.getJSONArray("data");
        List<FBAInvoiceVo> fbaInvoiceVoList = new ArrayList<>();

//        JSONArray relate_list = (JSONArray) inventoryListResult.get("relate_list");
//        if(true){
//            return;
//        }
        Set<String> collect7 = new HashSet<>();
        for (Object o : list) {
            JSONObject object = (JSONObject) o;
            JSONArray items = object.getJSONArray("items");
            for (Object o1 : items) {
                JSONObject object1 = (JSONObject) o1;
                collect7.add(object1.getString("sku"));
            }
        }
        //查询所有的产品信息
        QueryWrapper<Product> queryWrapper3 = new QueryWrapper();
        queryWrapper3.select("id,sku");
        queryWrapper3.in("sku", collect7);
        List<Product> list3 = productService.list(queryWrapper3);

        for (Object o : list) {
            JSONObject object = (JSONObject) o;
            FBAInvoiceVo fbaInvoiceVo = new FBAInvoiceVo();
            fbaInvoiceVo.setInoviceCode(object.getString("shipment_sn"));
            List<String> shipCode = new ArrayList<String>();
            if (hashMap.get(object.getString("shipment_sn")) != null) {
                JSONArray shipment_sn1 = (JSONArray) hashMap.get(object.getString("shipment_sn"));
                for (Object o1 : shipment_sn1) {
                    JSONObject object2 = (JSONObject) o1;
                    if (!shipCode.contains(object2.get("shipment_id"))) {
                        shipCode.add((String) object2.get("shipment_id"));
                    }
                }
            }
            fbaInvoiceVo.setShipmentCode(shipCode.size() > 0 ? shipCode.get(0) : null);
//            Warehouse warehouse1 = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getName, object.getString("wname")));
            Warehouse warehouse1 = list2.stream().filter(x -> x.getName().equals(object.getString("wname"))).findFirst().get();
            if (warehouse1 == null) {
//                throw new Exception(object.getString("wname") + "没有查到对应仓库");
                log.error(object.getString("wname") + "没有查到对应仓库");
                return;
            }
            fbaInvoiceVo.setDeliveryWarehouse(warehouse1.getId());
            fbaInvoiceVo.setTransportMode(object.getString("logistics_list_type"));
            fbaInvoiceVo.setLogisticsProvider(object.getString("logistics_provider_name"));
            fbaInvoiceVo.setLogisticsChannel(object.getString("logistics_channel_name"));
            //islockinventory
            fbaInvoiceVo.setIslockinventory("0");
            fbaInvoiceVo.setCreateUser(1L);
            JSONArray logistics = object.getJSONArray("logistics");
            if (logistics.size() > 0) {
                JSONObject logistics1 = (JSONObject) logistics.get(0);
                fbaInvoiceVo.setLogisticsTrackingNumber(logistics1.getString("tracking_number"));
            }
            fbaInvoiceVo.setLogisticsInfo(org.apache.commons.lang3.StringUtils.join(object.getJSONObject("head_logistics_list").getJSONArray("track_list"), ","));

            fbaInvoiceVo.setSendName(object.getString("shipment_user"));
            fbaInvoiceVo.setSendTime(object.getDate("shipment_time"));
            fbaInvoiceVo.setExpectReachTime(object.getDate("expected_arrival_date"));
            fbaInvoiceVo.setRealitySendTime(object.getDate("actual_shipment_time"));
            fbaInvoiceVo.setLogisticsCenterCode(object.getString("destination_fulfillment_center_id"));
            fbaInvoiceVo.setPaymentStatus(object.getString("pay_status"));
            fbaInvoiceVo.setInvoiceStatus("30");
            fbaInvoiceVo.setPrintNum(object.getIntValue("print_num"));
            if (fbaInvoiceVo.getPrintNum() != null && fbaInvoiceVo.getPrintNum() > 0) {
                fbaInvoiceVo.setPrintStatus("1");
            } else {
                fbaInvoiceVo.setPrintStatus("0");
            }
            fbaInvoiceVo.setPickTime(object.getDate("pick_time"));
            fbaInvoiceVo.setLxCreateUser(object.getString("create_user")); //创建人
            fbaInvoiceVo.setCreateTime(object.getDate("gmt_create"));
            fbaInvoiceVo.setIsPick(object.getString("is_pick"));


            // fbaInvoiceVo.setShipmentPlanTime(object.getDate("shipment_time"));// 计划发货时间 无
            fbaInvoiceVo.setLogisticsStatus(object.getString("order_logistics_status"));
            // fbaInvoiceVo.seVat(object.getString("shipment_time"));  //税号？
            //物流预计时效
            //fbaInvoiceVo.setAllocationType(object.getString("aux_head_fee_type"));分摊类型？
            fbaInvoiceVo.setRemark(object.getString("remark"));
            // fbaInvoiceVo.setPrincipal(object.getString("shipment_time"));  //负责人 无
            JSONArray fileList = object.getJSONArray("fileList");
            fbaInvoiceVo.setFile(org.apache.commons.lang3.StringUtils.join(fileList, ","));  //fileList
            //object.getString("sname"); //获取店铺名称查询对应店铺
            //items 文档上是商品
            JSONArray items = object.getJSONArray("items");
            List<FBAInvoiceDetailItemVo> invoiceDetailList = new ArrayList<>();
            for (Object o1 : items) {
                FBAInvoiceDetailItemVo fbaInvoiceDetailItemVo = new FBAInvoiceDetailItemVo();
                JSONObject object1 = (JSONObject) o1;

//                ShopInfo shopInfo = shopInfoService.getOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getShopName, object1.getString("sname")));
                //list4
                ShopInfo shopInfo = list4.stream().filter(x -> x.getShopName().equals(object1.getString("sname"))).findFirst().get();
                if (shopInfo == null) {
//                    throw new Exception(object1.getString("sname") + "没有查到对应店铺");
                    log.error(object1.getString("sname") + "没有查到对应店铺");
                    return;
                }
                fbaInvoiceDetailItemVo.setShopId(shopInfo.getId());//店铺object1.getLong("sid")
//                Warehouse warehouse = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getName, object1.getString("wname")));
                Warehouse warehouse = list2.stream().filter(x -> x.getName().equals(object.getString("wname"))).findFirst().get();
                if (warehouse == null) {
//                    throw new Exception(object1.getString("wname") + "没有查到对应仓库");
                    log.error(object1.getString("wname") + "没有查到对应仓库");
                    return;
                }
                fbaInvoiceDetailItemVo.setWarehouse(warehouse.getId());//仓库
//                Product product = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, object1.getString("sku")));
                Product product = list3.stream().filter(x -> x.getSku().equals(object1.getString("sku"))).findFirst().get();
                if (product == null) {
//                    throw new Exception(object1.getString("sku") + "没有查到对应产品");//
                    log.error(object1.getString("sku") + "没有查到对应产品");
                    return;
                }
                fbaInvoiceDetailItemVo.setPicUrl(product.getPicUrl());
                //listingFatherServiceImpl
                fbaInvoiceDetailItemVo.setName(product.getId());//产品id

                fbaInvoiceDetailItemVo.setMsku(object1.getString("msku"));
                if (!ObjectUtils.isEmpty(object1.getString("fnsku"))) {
                    fbaInvoiceDetailItemVo.setFnsku(object1.getString("fnsku"));
                }
                //fbaInvoiceDetailItemVo.setName(object1.getLong("product_id"));//待转
                fbaInvoiceDetailItemVo.setSku(object1.getString("sku"));
                fbaInvoiceDetailItemVo.setCountry(object1.getString("nation")); //国家
                fbaInvoiceDetailItemVo.setPlanShipCode(object1.getString("isp_id")); //计划id 转换？
                // 货件单号 ？
                fbaInvoiceDetailItemVo.setPackageLength(object1.getBigDecimal("cg_package_length"));//包装规格长
                fbaInvoiceDetailItemVo.setPackageWidth(object1.getBigDecimal("cg_package_width"));
                fbaInvoiceDetailItemVo.setPackageHeight(object1.getBigDecimal("cg_package_height"));
                fbaInvoiceDetailItemVo.setOneSuttle(object1.getBigDecimal("cg_box_net_weight"));// 单箱净重
                fbaInvoiceDetailItemVo.setOneGross(object1.getBigDecimal("cg_product_gross_weight"));// 商品毛重（
                fbaInvoiceDetailItemVo.setTotalSuttle(object1.getBigDecimal("total_nw"));//总净重（G）
                fbaInvoiceDetailItemVo.setTotalGross(object1.getBigDecimal("total_gw"));//总毛重（G）
                fbaInvoiceDetailItemVo.setPlanSendQuantity(object1.getIntValue("shipment_plan_quantity"));//计划发货量

                fbaInvoiceDetailItemVo.setDeclarationQuantity(object1.getIntValue("apply_num"));//申报量
                fbaInvoiceDetailItemVo.setTaxAmount(object1.getBigDecimal("tax_amount"));//税费
                fbaInvoiceDetailItemVo.setSendQuantity(object1.getIntValue("num"));//发货数量
                // fbaInvoiceDetailItemVo.setShipmentShop(object1.getString("sname"));//发货仓库店铺
                //object1.getString("seller_name")shipmentShop
                if (object1.getString("seller_name") != null && !object1.getString("seller_name").equals("")) {
                    fbaInvoiceDetailItemVo.setShipmentShop(shopInfo.getId());//发货仓库店铺
                } else {

                }
                fbaInvoiceDetailItemVo.setShipmentCode(object1.getString("shipment_id"));//shipment_id
                if (object1.getString("fnsku") != null && !object1.getString("fnsku").equals("")) {
                    fbaInvoiceDetailItemVo.setShipmentShopFnsku(object1.getString("fnsku"));
                }
                //发货仓库FUSKU
                // fbaInvoiceDetailItemVo.setWarehouseBin(object1.getLong(""));//仓位(数量)??
                //   fbaInvoiceDetailItemVo.setPicUrl(object1.getString("pic_url"));//图片URL
                JSONArray whbCodeList = object1.getJSONArray("whb_code_list");
                if (whbCodeList != null && whbCodeList.size() > 0) {
                    JSONObject whbCode = (JSONObject) whbCodeList.get(0);
                    fbaInvoiceDetailItemVo.setWhbCode(whbCode.getString("whb_code"));//仓位编码
                    //查询仓位
                    WarehouseBin whbCode1 = warehouseBinService.getOne(Wrappers.lambdaQuery(WarehouseBin.class)
                            .eq(WarehouseBin::getStorageBin, whbCode.getString("whb_code")));
                    if (whbCode1 != null) {
                        //outBingId
                        fbaInvoiceDetailItemVo.setWarehouseBin(whbCode1.getId());
                        fbaInvoiceDetailItemVo.setOutBingId(whbCode1.getId());
                    } else {
                        throw new Exception("仓位编码不存在");
                    }
                }
                invoiceDetailList.add(fbaInvoiceDetailItemVo);
            }
            fbaInvoiceVo.setInvoiceDetailList(invoiceDetailList);
            fbaInvoiceVoList.add(fbaInvoiceVo);
        }
        for (FBAInvoiceVo fbaInvoiceVo : fbaInvoiceVoList) {
            try {
                FBAInvoice one = fbaInvoiceMapper.selectOne(Wrappers.lambdaQuery(FBAInvoice.class).eq(FBAInvoice::getInoviceCode, fbaInvoiceVo.getInoviceCode()));
                if (one != null) {
                    continue;
                }
                fbaInvoiceService.create(fbaInvoiceVo);
//                fbaInvoiceService.shipping(Arrays.asList(fbaInvoiceVo.getId()));
            } catch (Exception e) {
                log.error("FBA发货单同步添加失败", e);
            }
        }
    }

    @Override
    public void InboundShipmentSendGoods(List<Long> ids) throws Exception {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        List<FBAInvoice> list = fbaInvoiceMapper.selectBatchIds(ids);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        JSONArray jsonArray = new JSONArray();
        for (FBAInvoice f : list) {
            jsonArray.add(f.getInoviceCode());
        }
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("shipment_nos", jsonArray);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", getToken());
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询销FBA发货单列表详情 批量
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, InboundShipmentSendGoods_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "发货单发货失败：" + inventoryListResult.getString("msg"));
        }
        log.info(">>>>>>>>>>发货单发货成功：");
    }

    @Override
    public void syncshipmentList() {
        Integer length = 1000;
        Integer offset = 0;
        String shopCode = lingXingInterfaceMapper.getShopCode();
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("sid", shopCode);
        requestBody.put("offset", offset);
        requestBody.put("length", length);
        requestBody.put("start_date", "2019-01-01");
        requestBody.put("end_date", "2023-08-10");
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, ShipmentList_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        System.out.println(inventoryListResult.getString("total"));
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody, ShipmentList_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
            }
        }
//        int intValue = inventoryListResult.getJSONObject("data").getIntValue("total");
//        System.out.println(intValue);
        addshipmentList(inventoryListResult.getJSONObject("data").getJSONArray("list"));
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total") - offset - length;
        System.out.println(total);
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i <= pageNum; i++) {
                offset = offset + length;
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("sid", shopCode);
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);
                requestBody1.put("start_date", "2019-01-01");
                requestBody1.put("end_date", "2023-08-10");
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, ShipmentList_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
//                System.out.println(inventoryListResult.getInteger("code") + ".........");
                if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                    JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, requestBody1, ShipmentList_URL);
                    if (jsonObject == null) {
                        return;
                    }
                    if (jsonObject.getInteger("code") == 0) {
                        continueSearchResultJSON = new JSONObject();
                        continueSearchResultJSON = jsonObject;
                    } else {
                        Assert.isTrue(false, "查询仓库列表失败，原因：code不为零查询失败");
                    }
                }
//                System.out.println(continueSearchResultJSON.getJSONObject("data").getIntValue("total"));
                //转换成并存库
                addshipmentList(continueSearchResultJSON.getJSONObject("data").getJSONArray("list"));
            }
        }
    }

    private void addshipmentList(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
        List<FbaShipment> fbaShipments = new ArrayList<>();
        List<FbaShipmentProduct> fbaShipmentProducts = new ArrayList<>();
        for (Object t : result) {
            JSONObject o = (JSONObject) t;
            FbaShipment vo = new FbaShipment();
            Long ID = IdWorker.getId(vo);
            vo.setId(ID);
            vo.setShipmentId(o.getString("shipment_id"));//货件编号
            vo.setShipmentName(o.getString("shipment_name"));//货件名称
            ShopInfo info = shopInfoMapper.selectOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getShopCode, o.getString("sid")));
            if (info != null) {
                vo.setShop(info.getId());//店铺
            }
            vo.setDestinationFulfillmentCenterId(o.getString("destination_fulfillment_center_id"));//物流中心编码
            vo.setSyncTime(o.getString("sync_time"));//同步时间
            vo.setShipmentStatus(o.getString("shipment_status"));//货件状态
            vo.setIsClosed(o.getString("is_closed"));//是否已完成状态
//            vo.setSeller(o.getString("seller"));//店铺名称
            vo.setIsSynchronous(o.getString("is_synchronous"));//是否从亚马逊后台同步还是erp创建
            vo.setIsUploadedBox(o.getString("is_uploaded_box"));//是否上传了装箱信息
//            vo.setWorkingTime(o.getString("working_time"));//WORKING时间
//            vo.setShippedTime(o.getString("shipped_time"));//SHIPPED时间
//            vo.setReceivingTime(o.getString("receiving_time"));//RECEIVING时间
//            vo.setClosedTime(o.getString("closed_time"));//CLOSED时间
            vo.setReferenceId(o.getString("reference_id"));
            JwtUserInfo currentUser = JwtUserInfo.fromHeader();
            FbaShipment entity = new FbaShipment();
            BeanUtils.copyProperties(vo, entity);
            entity.setCreateTime(new Date());
            entity.setLastUpdateTime(new Date());
            if (currentUser != null) {
                entity.setCreateUser(currentUser.getUserId());
                entity.setLastUpdateUser(currentUser.getUserId());
            }

            if (vo.getPackingType() == null) {
                entity.setPackingType("1");
            }
            JSONArray item_list = o.getJSONArray("item_list");
            for (Object p : item_list) {
                JSONObject proInfo = (JSONObject) p;
                FbaShipmentProduct fbaShipmentProductItemVo = new FbaShipmentProduct();
                fbaShipmentProductItemVo.setParentFbaShipment(ID);
                fbaShipmentProductItemVo.setMsku(proInfo.getString("msku"));
                fbaShipmentProductItemVo.setFnsku(proInfo.getString("fnsku"));
                fbaShipmentProductItemVo.setAmountDeclared(proInfo.getInteger("quantity_shipped"));//申报量
                fbaShipmentProductItemVo.setQuantityShippedLocal(proInfo.getInteger("quantity_shipped_local"));//已发货
                fbaShipmentProductItemVo.setQuantityReceived(proInfo.getInteger("quantity_received"));//签收量
                fbaShipmentProductItemVo.setShenFaDifference(proInfo.getInteger("quantity_shipped") - proInfo.getInteger("quantity_shipped_local"));//申发差异
                fbaShipmentProductItemVo.setShouFaDifference(proInfo.getInteger("quantity_shipped_local") - proInfo.getInteger("quantity_received"));//收发差异
                fbaShipmentProductItemVo.setShenShouDifference(proInfo.getInteger("quantity_shipped") - proInfo.getInteger("quantity_received"));//申收差异
                fbaShipmentProductItemVo.setQuantityPerCarton(proInfo.getInteger("quantity_in_case"));//单箱数量
                if (proInfo.getJSONArray("shipment_plan_list").size() != 0) {
                    String shipmentPlanSn = ((JSONObject) proInfo.getJSONArray("shipment_plan_list").get(0)).getString("shipment_plan_sn");
                    fbaShipmentProductItemVo.setShipmentPlanSn(shipmentPlanSn);
                }
                fbaShipmentProductItemVo.setCreateUser(entity.getCreateUser());
                fbaShipmentProductItemVo.setLastUpdateUser(entity.getLastUpdateUser());
                fbaShipmentProductItemVo.setCreateTime(new Date());
                fbaShipmentProducts.add(fbaShipmentProductItemVo);
            }
            fbaShipments.add(entity);
        }
        fbaShipmentService.saveBatch(fbaShipments, fbaShipments.size());
        fbaShipmentProductService.saveBatch(fbaShipmentProducts, fbaShipmentProducts.size());
    }

    //拉取调拨单
    public void saveRequisition() {
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap();
        int pageSize = 50;
        int page = 1;
        requestBody.put("page", page);
        requestBody.put("page_size", pageSize);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询调拨单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, StorageAllocationList_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody, StorageAllocationList_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询调拨单列表失败，原因：code不为零查询失败");
            }
        }

        addStorageAllocationList(inventoryListResult.getJSONArray("data"));
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total");
        for (int i = 1; i < total / 50 + 1; i++) {
            page = page + 1;
            JSONObject object1 = new JSONObject();
            object1.put("page", page);
            object1.put("page_size", pageSize);
            object1.put("status_arr", 3);
            //定义URL参数
            Map<String, Object> requestParams1 = new HashMap<>();
            requestParams1.put("access_token", token);
            requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
            requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
            Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    requestParams1, StorageAllocationList_URL,
                    null, object1);
            JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
            if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, object1, StorageAllocationList_URL);
                if (jsonObject == null) {
                    return;
                }
                if (jsonObject.getInteger("code") == 0) {
                    continueSearchResultJSON = new JSONObject();
                    continueSearchResultJSON = jsonObject;
                } else {
                    Assert.isTrue(false, "查询调拨单列表失败，原因：code不为零查询失败");
                }
            }
            //转换成并存库
            addStorageAllocationList(continueSearchResultJSON.getJSONArray("data"));
        }
    }

    //保存调拨单
    private void addStorageAllocationList(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
        for (Object t : result) {
            JSONObject o = (JSONObject) t;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date1 = dateFormat.parse(o.getString("create_time"));
                Date date2 = dateFormat.parse("2023-8-21");
                if (!date1.before(date2)) {
                    continue;
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            RequisitionVo requisitionVo = new RequisitionVo();
            requisitionVo.setRqtSn(o.getString("order_sn"));//调拨单号

            Warehouse wid = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getWid, o.getString("wid")));
            if (wid != null) {
                requisitionVo.setWid(wid.getId()); //出库仓库id
            }
            Warehouse toWid = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getWid, o.getString("to_wid")));
            if (wid != null) {
                requisitionVo.setToWid(toWid.getId()); //入库仓库id
            }
            requisitionVo.setStatus(o.getString("status")); //单据状态
            requisitionVo.setFreightFee(new BigDecimal(o.getString("freight_fee"))); //运费
            requisitionVo.setOtherFee(new BigDecimal(o.getString("other_fee"))); //其他运费
            requisitionVo.setRemark(o.getString("remark"));//单据备注
            //子表
            JSONArray item_list = o.getJSONArray("item_list");
            List<RequisitionProductItemVo> requisitionProductVos = new ArrayList<>();
            for (Object p : item_list) {
                JSONObject a = (JSONObject) p;
                System.out.println(a.toString());
                RequisitionProductItemVo requisitionProductVo = new RequisitionProductItemVo();
                //requisitionProductVo.setImg(((JSONObject) p).getString("pic_url")); //图片
                Product product = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, a.getString("sku")));
                if (product != null) {
                    requisitionProductVo.setProductId(product.getId());
                    requisitionProductVo.setProductIdName(product.getName());
                }
                requisitionProductVo.setSku(a.getString("sku")); // sku
                requisitionProductVo.setFnsku(a.getString("fnsku")); //fnsku
                requisitionProductVo.setShopName(a.getLong("seller_id")); //店铺id
                requisitionProductVo.setAvailbleRqtNum(a.getInteger("product_good_num"));//可用调拨量
                requisitionProductVo.setDefectiveQuantity(a.getInteger("product_bad_num"));//次品调拨量
                requisitionProductVo.setBasisWeight(a.getBigDecimal("cg_product_gross_weight"));//单品重量
                //入库可用仓位
                WarehouseBin bin = warehouseBinMapper.selectOne(Wrappers.lambdaQuery(WarehouseBin.class).eq(WarehouseBin::getStorageBin, a.getString("to_available_bin")));
                if (bin != null) {
                    requisitionProductVo.setToGoodWarehouseBin(bin.getId());
                }
                //入库次品仓位
                WarehouseBin bin2 = warehouseBinMapper.selectOne(Wrappers.lambdaQuery(WarehouseBin.class).eq(WarehouseBin::getStorageBin, a.getString("to_available_bin")));
                if (bin2 != null) {
                    requisitionProductVo.setToBadWarehouseBin(bin2.getId());
                }
                requisitionProductVo.setRemark(a.getString("product_remark")); //产品备注
                requisitionProductVos.add(requisitionProductVo);
            }
            requisitionVo.setRequisitionProduct(requisitionProductVos);
            try {
                Long aLong = requisitionService.create(requisitionVo);
                Requisition a = new Requisition();
                a.setId(aLong);
                a.setCreateUser(10999L);
                requisitionMapper.updateById(a);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    //保存调整单
    private void addAdjustmentOrder(JSONArray result) {
//        if (Objects.isNull(result)) {
//            return;
//        }
        for (Object t : result) {
            JSONObject o = (JSONObject) t;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date1 = dateFormat.parse(o.getString("create_time"));
                Date date2 = dateFormat.parse("2023-8-21");
                if (!date1.before(date2)) {
                    continue;
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            AdjustmentOrderVo adjustmentOrderVo = new AdjustmentOrderVo();
            adjustmentOrderVo.setOrderSn(o.getString("order_sn")); // 调整单单号
            //仓库
            Warehouse wid = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class).eq(Warehouse::getWid, o.getLong("wid")));
            if (wid != null) {
                adjustmentOrderVo.setWid(o.getLong("wid"));
            }
            adjustmentOrderVo.setType(o.getString("type"));
            adjustmentOrderVo.setRemark(o.getString("remark"));
            adjustmentOrderVo.setStatus(o.getString("status")); //状态
            //子表
            JSONArray item_list = o.getJSONArray("item_list");
            List<AdjustmentOrderProductItemVo> adjustmentOrderProductItemVos = new ArrayList<>();
            for (Object p : item_list) {
                JSONObject a = (JSONObject) p;
                AdjustmentOrderProductItemVo adjustmentOrderProductItemVo = new AdjustmentOrderProductItemVo();
                //adjustmentOrderProductItemVo.setPicUrl(); //
                //
                Product sku = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, a.getString("sku")));
                if (sku != null) {
                    adjustmentOrderProductItemVo.setPrdName(sku.getId());
                    adjustmentOrderProductItemVo.setPrdLabel(sku.getLabel());
                }
                adjustmentOrderProductItemVo.setProduct(a.getString("product_name")); //
                adjustmentOrderProductItemVo.setSku(a.getString("sku")); //
                //店铺id
                ShopInfoVo sellerId = shopInfoMapper.selectVoById(a.getLong("seller_id"));
                if (sellerId != null) {
                    adjustmentOrderProductItemVo.setShop(sellerId.getId());
                }
                if (a.getString("type") != null && a.getString("type").equals("1")) {
                    //新Fnsku
                    ListingFather toFnsku = listingFatherMapper.selectOne(Wrappers.lambdaQuery(ListingFather.class)
                            .eq(ListingFather::getFnsku, a.getString("to_fnsku")));
                    if (toFnsku != null) {
                        adjustmentOrderProductItemVo.setNewFnsku(toFnsku.getId());
                    }
                    //新店铺
                    ShopInfoVo sellerId2 = shopInfoMapper.selectVoById(a.getLong("to_seller_id"));
                    if (sellerId2 != null) {
                        adjustmentOrderProductItemVo.setNewShop(sellerId2.getId());
                    }
                }
                //可用调整量
                adjustmentOrderProductItemVo.setGoodAdjustNum(a.getLong("adjustment_valid_num"));
                //次品调整量
                adjustmentOrderProductItemVo.setBadAdjustNum(a.getLong("adjustment_bad_num"));
                if (a.getString("type") != null && a.getString("type").equals("0")) {
                    //新可用仓位
                    WarehouseBin bin = warehouseBinMapper.selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                            .eq(WarehouseBin::getStorageBin, a.getString("available_bin")));
                    if (bin != null) {
                        adjustmentOrderProductItemVo.setNewGoodWhb(bin.getId());
                    }
                    //新次品仓位
                    WarehouseBin bin2 = warehouseBinMapper.selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                            .eq(WarehouseBin::getStorageBin, a.getString("inferior_bin")));
                    if (bin2 != null) {
                        adjustmentOrderProductItemVo.setNewBadWhb(bin2.getId());
                    }
                }
                adjustmentOrderProductItemVo.setRemark(a.getString("product_remark"));
                adjustmentOrderProductItemVos.add(adjustmentOrderProductItemVo);
            }
            adjustmentOrderVo.setProductLists(adjustmentOrderProductItemVos);
            try {
                Long aLong = adjustmentOrderService.create(adjustmentOrderVo);
                AdjustmentOrder a = new AdjustmentOrder();
                a.setId(aLong);
                a.setCreateUser(10999L);
                adjustmentOrderMapper.updateById(a);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    //拉取调整单
    public void saveAdjustmentOrder() {
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap();
        int pageSize = 200;
        int page = 1;
        requestBody.put("page", page);
        requestBody.put("page_size", pageSize);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询调整单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, AdjustmentOrderList_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody, AdjustmentOrderList_URL);
            if (jsonObject == null) {
                return;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询调整单列表失败，原因：code不为零查询失败");
            }
        }
        addAdjustmentOrder(inventoryListResult.getJSONArray("data"));
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total");
        for (int i = 1; i < total / 200 + 1; i++) {
            page = page + 1;
            JSONObject object1 = new JSONObject();
            object1.put("page", page);
            object1.put("page_size", pageSize);
            object1.put("status_arr", 3);
            //定义URL参数
            Map<String, Object> requestParams1 = new HashMap<>();
            requestParams1.put("access_token", token);
            requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
            requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
            Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    requestParams1, AdjustmentOrderList_URL,
                    null, object1);
            JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
            if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, object1, AdjustmentOrderList_URL);
                if (jsonObject == null) {
                    return;
                }
                if (jsonObject.getInteger("code") == 0) {
                    continueSearchResultJSON = new JSONObject();
                    continueSearchResultJSON = jsonObject;
                } else {
                    Assert.isTrue(false, "查询调整单列表失败，原因：code不为零查询失败");
                }
            }
            //转换成并存库
            addAdjustmentOrder(continueSearchResultJSON.getJSONArray("data"));
        }
    }

    //保存盘点单
    private void addInventoryList(JSONObject result) {
        if (Objects.isNull(result)) {
            return;
        }
        JSONObject o = result;
        InventoryListVo inventoryListVo = new InventoryListVo();
        inventoryListVo.setInventoryNumber(o.getString("order_sn")); //盘点单单号
        inventoryListVo.setWarehouseStock(o.getLong("wid"));//盘点仓库id
        inventoryListVo.setInventoryType(o.getString("check_type"));//盘点类型
        inventoryListVo.setProductCategory(o.getString("product_type"));//
        inventoryListVo.setCountPeople(o.getLong("check_uid"));//
        inventoryListVo.setStatus(o.getString("status"));//
        inventoryListVo.setBlindPlate(o.getString(o.getString("is_display_check")));//
        inventoryListVo.setZeroParticipation(o.getBoolean("is_zero"));//
        inventoryListVo.setRemark(o.getString("remark"));//
        //
        JSONArray product_list = o.getJSONArray("product_list");
        List<InventoryListSubtableItemVo> list = new ArrayList<>();
        for (Object p : product_list) {
            JSONObject a = (JSONObject) p;
            InventoryListSubtableItemVo vo = new InventoryListSubtableItemVo();
            vo.setTradeName(a.getLong("product_id"));//
            vo.setSku(a.getString("sku"));//
            vo.setFnsku(a.getString("fnsku"));//
            vo.setShop(a.getLong("seller_id"));//
            vo.setShippingSpace(a.getLong("whb_id"));//
            vo.setShippingSpaceType(a.getString("whb_type"));//
            vo.setInventory(a.getInteger("book_inventory"));//
            vo.setFirmInventory(a.getInteger("actual_inventory"));//
            vo.setIntensityDifference(a.getInteger("different_count"));//
            vo.setRemark(a.getString("remark"));
            list.add(vo);
        }
        inventoryListVo.setGenerateInventoryDetails(list);
        try {
            Long aLong = inventoryListService.create(inventoryListVo);
            InventoryList a = new InventoryList();
            a.setId(aLong);
            a.setCreateUser(10999L);
            inventoryListMapper.updateById(a);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //拉取盘点单
    public void saveInventoryList() {
        int pageSize = 50;
        int page = 1;
        Map<String, Object> requestBody = new HashMap();
        requestBody.put("page", page);
        requestBody.put("page_size", pageSize);
        ArrayList<String> arrayList = InventoryList();
        for (String a : arrayList) {
            requestBody.put("order_sn", a);
            Map<String, Object> requestParams = new HashMap<>();
            //获取token
            String token = getToken();
            //定义URL参数
            requestParams.put("access_token", token);
            requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
            requestParams.put("timestamp", System.currentTimeMillis() / 1000);
            Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    requestParams, InventoryList_URL,
                    null, requestBody);
            JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
            if (inventoryListResult.getInteger("code") != 0) {
                JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody, InventoryList_URL);
                if (jsonObject == null) {
                    return;
                }
                if (jsonObject.getInteger("code") == 0) {
                    inventoryListResult = new JSONObject();
                    inventoryListResult = jsonObject;
                } else {
                    Assert.isTrue(false, "查询盘点单列表失败，原因：code不为零查询失败");
                }
            }
            addInventoryList(inventoryListResult.getJSONObject("data"));
            //判断数据是否取完,若未取完，继续取数据
            Integer total = inventoryListResult.getInteger("total");
            for (int i = 1; i < total / 50 + 1; i++) {
                page = page + 1;
                JSONObject object1 = new JSONObject();
                object1.put("page", page);
                object1.put("page_size", pageSize);
                object1.put("status_arr", 3);
                //定义URL参数
                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", token);
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                        requestParams1, InventoryList_URL,
                        null, object1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                    JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, object1, InventoryList_URL);
                    if (jsonObject == null) {
                        return;
                    }
                    if (jsonObject.getInteger("code") == 0) {
                        continueSearchResultJSON = new JSONObject();
                        continueSearchResultJSON = jsonObject;
                    } else {
                        Assert.isTrue(false, "查询盘点单列表失败，原因：code不为零查询失败");
                    }
                }
                //转换成并存库
                addInventoryList(continueSearchResultJSON.getJSONObject("data"));
            }
        }

    }

    /**
     * 拉取用户
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void getCustomer() {
        Map<String, Object> requestBody = new HashMap<>();
//        requestBody.put("time_search_type",Integer.parseInt(jsonObject.get("time_search_type").toString()));
//        requestBody.put("start_date",jsonObject.get("start_date").toString());
//        requestBody.put("end_date",jsonObject.get("end_date").toString());
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", getToken());
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询销FBA发货单列表详情 批量
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Get.getValue(),
                requestParams, Customer_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        JSONArray objects = JSONObject.parseArray(inventoryListResult.getString("data"));
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "获取用户失败：" + inventoryListResult.getString("msg"));
        }
        try {
            if (objects != null && objects.size() > 0) {
                for (Object o : objects) {
                    JSONObject obj = (JSONObject) o;
                    Integer uid = obj.getInteger("uid");
                    SysUser sysUser = sysUserMapper.selectById(uid);
                    if (sysUser == null) {
                        sysUser = new SysUser();
                        sysUser.setId(uid.longValue());
                        sysUser.setName(obj.getString("realname"));
                        sysUser.setUsername(obj.getString("username"));
                        sysUser.setMobile(obj.getString("mobile"));
                        sysUser.setVerifiedMail(obj.getString("email"));
                        if (obj.getInteger("status") == 1) {
                            sysUser.setAvatar("0");
                        } else {
                            sysUser.setAvatar("1");
                        }
                        sysUser.setDelFlag(false);
                        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        if (obj.get("create_time") != null) {
                            String createTime = obj.getString("create_time") + ":00";
                            sysUser.setCreateTime(sim.parse(createTime));
                        }
                        sysUser.setPassword(passwordEncoder.encode("123456"));
                        int insert = sysUserMapper.insert(sysUser);
                        if (insert > 0) {
                            SysUserRole role = new SysUserRole();
                            role.setCreateTime(new Date());
                            role.setUserId(sysUser.getId());
                            QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("role_name", "临时用户");
                            SysRole sysRole = sysRoleMapper.selectOne(queryWrapper);
                            if (sysRole != null) {
                                role.setRoleId(sysRole.getId());
                                sysUserRoleMapper.insert(role);
                            }
                        }
                    } else {
                        sysUser.setName(obj.getString("realname"));
                        sysUser.setUsername(obj.getString("username"));
                        sysUser.setMobile(obj.getString("mobile"));
                        sysUser.setVerifiedMail(obj.getString("email"));
                        if (obj.getInteger("status") == 1) {
                            sysUser.setAvatar("0");
                        } else {
                            sysUser.setAvatar("1");
                        }
                        sysUser.setLastUpdateTime(new Date());
//                    sysUser.setPassword(passwordEncoder.encode("123456"));
                        sysUserMapper.updateById(sysUser);
                    }
                }
            }
        } catch (Exception e) {
            log.error("添加用户信息异常--------" + e.getMessage());
        }


    }

    //查询盘点单单号
    private ArrayList<String> InventoryList() {
        //获取token
        String token = getToken();
        Map<String, Object> requestBody = new HashMap();
        int pageSize = 50;
        int page = 1;
        requestBody.put("page", page);
        requestBody.put("page_size", pageSize);
        Map<String, Object> requestParams = new HashMap<>();
        //定义URL参数
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询盘点单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, "https://openapi.lingxing.com/erp/sc/routing/inventoryReceipt/InventoryCheck/getOrderList",
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            JSONObject jsonObject = regainLingXingData(inventoryListResult, requestBody,
                    "https://openapi.lingxing.com/erp/sc/routing/inventoryReceipt/InventoryCheck/getOrderList");
            if (jsonObject == null) {
                return null;
            }
            if (jsonObject.getInteger("code") == 0) {
                inventoryListResult = new JSONObject();
                inventoryListResult = jsonObject;
            } else {
                Assert.isTrue(false, "查询盘点单单号失败，原因：code不为零查询失败");
            }
        }
        ArrayList<String> arrayList = new ArrayList<>();
        JSONArray data2 = inventoryListResult.getJSONArray("data");
        if (Objects.isNull(data2)) {
            return null;
        }
        for (Object t : data2) {
            JSONObject o = (JSONObject) t;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date1 = dateFormat.parse(o.getString("create_time"));
                Date date2 = dateFormat.parse("2023-8-21");
                if (!date1.before(date2)) {
                    continue;
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            arrayList.add(o.getString("order_sn"));
        }
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total");
        for (int i = 1; i < total / 50 + 1; i++) {
            page = page + 1;
            JSONObject object1 = new JSONObject();
            object1.put("page", page);
            object1.put("page_size", pageSize);
            object1.put("status_arr", 3);
            //定义URL参数
            Map<String, Object> requestParams1 = new HashMap<>();
            requestParams1.put("access_token", token);
            requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
            requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
            Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                    requestParams1, "https://openapi.lingxing.com/erp/sc/routing/inventoryReceipt/InventoryCheck/getOrderList",
                    null, object1);
            JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
            if (!"0".equals(continueSearchResultJSON.get("code").toString())) {
                JSONObject jsonObject = regainLingXingData(continueSearchResultJSON, object1,
                        "https://openapi.lingxing.com/erp/sc/routing/inventoryReceipt/InventoryCheck/getOrderList");
                if (jsonObject == null) {
                    return null;
                }
                if (jsonObject.getInteger("code") == 0) {
                    continueSearchResultJSON = new JSONObject();
                    continueSearchResultJSON = jsonObject;
                } else {
                    Assert.isTrue(false, "查询盘点单单号失败，原因：code不为零查询失败");
                }
            }
            //转换成并存库
            JSONArray data = continueSearchResultJSON.getJSONArray("data");
            if (Objects.isNull(data)) {
                return null;
            }
            for (Object t : data) {
                JSONObject o = (JSONObject) t;
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date1 = dateFormat.parse(o.getString("create_time"));
                    Date date2 = dateFormat.parse("2023-8-21");
                    if (!date1.before(date2)) {
                        continue;
                    }
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                arrayList.add(o.getString("order_sn"));
            }
        }
        return arrayList;
    }


    /**
     * 网络图片转MultipartFile
     *
     * @param strUrl
     * @return
     * @throws IOException
     */
    public static MultipartFile onlineAddressTransferFile(String strUrl) throws IOException {
        InputStream stream = getInputStreamByUrl(strUrl);
        if (!ObjectUtils.isEmpty(stream)) {
            MultipartFile file = new MockMultipartFile("网络图片", FileUtil.getName(strUrl), "image/jpeg", stream);
            return file;
        }
        return null;
    }

    /**
     * 根据地址获得数据的输入流
     *
     * @param strUrl 网络连接地址
     * @return url的输入流
     */
    public static InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(strUrl)) {
                URL url = new URL(strUrl);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(20 * 1000);
                final ByteArrayOutputStream output = new ByteArrayOutputStream();
                IOUtils.copy(conn.getInputStream(), output);
                return new ByteArrayInputStream(output.toByteArray());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public void syncClassify() {

        //获取token
        String token = getToken();
        //定义分页参数
        Integer offset = 0;
        Integer length = 1000;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);

        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询出库单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Get.getValue(),
                requestParams, CLASSIFY_URL,
                null, requestBody);
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询销售出库单列表失败，原因：" + inventoryListResult.getString("msg"));
        }
        JSONArray result = inventoryListResult.getJSONArray("data");
        //转换成并存库
        saveClassify(result);
        //判断数据是否取完,若未取完，继续取数据
        Integer total = inventoryListResult.getInteger("total");
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = i * length;
                //定义查询参数
                Map<String, Object> requestBody1 = new HashMap<>();
                requestBody1.put("offset", offset);
                requestBody1.put("length", length);

                Map<String, Object> requestParams1 = new HashMap<>();
                requestParams1.put("access_token", getToken());
                requestParams1.put("app_key", REQUEST_PARAMS.get("appId"));
                requestParams1.put("timestamp", System.currentTimeMillis() / 1000);
                //查询出库单列表
                Object continueSearch = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Get.getValue(),
                        requestParams1, CLASSIFY_URL,
                        null, requestBody1);
                JSONObject continueSearchResultJSON = (JSONObject) continueSearch;
                if (inventoryListResult.getInteger("code") != 0) {
                    Assert.isTrue(false, "查询销售出库单列表失败，原因：" + continueSearchResultJSON.getString("msg"));
                }
                JSONArray continueSearchResult = continueSearchResultJSON.getJSONArray("data");
                //转换成并存库
                saveClassify(continueSearchResult);
            }
        }
        log.info(">>>>>>>>>>同步完成：" + total);
    }

    @Transactional(rollbackFor = Exception.class)
    public void AdjustmentForm(JSONArray result) throws Exception {
        //获取token
        String token = getToken();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = dateFormat.format(new Date());
        //定义分页参数
        Integer offset = 0;
        Integer length = 100;
        //定义查询参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("offset", offset);
        requestBody.put("length", length);
//        requestBody.put("page", offset);
//        requestBody.put("page_size", length);
        requestBody.put("search_date_type", "1");//时间类型 1 创建时间 2 调整时间 3 更新时间
//        requestBody.put("adjust_status", "121");//121 待审批
        requestBody.put("start_date", format);
        requestBody.put("end_date", format);
        //定义URL参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("app_key", REQUEST_PARAMS.get("appId"));
        requestParams.put("timestamp", System.currentTimeMillis() / 1000);
        //查询调整单列表
        Object inventoryListResultObj = restUtilLingXing.lingXingRequest("2", RequestMethodKind.Post.getValue(),
                requestParams, STORAGEADJUSTORDER_URL,
                null, requestBody);
        System.out.println(inventoryListResultObj.toString());
        JSONObject inventoryListResult = (JSONObject) inventoryListResultObj;
        if (inventoryListResult.getInteger("code") != 0) {
            Assert.isTrue(false, "查询调整单接口失败，原因：" + inventoryListResult.getString("msg"));
        }
        adjustmentOrder adjustmentOrder = JSON.parseObject(inventoryListResultObj.toString(), adjustmentOrder.class);
        if (adjustmentOrder.getCode() == 0) {
            List<adjustmentOrder.DataBean> data = adjustmentOrder.getData();
            for (int i = 0; i < data.size(); i++) {
                adjustmentOrder.DataBean dataBean = data.get(i);
                AdjustmentOrder adjustmentOrder2 = adjustmentOrderService.getOne(Wrappers.lambdaQuery(AdjustmentOrder.class)
                        .eq(AdjustmentOrder::getOrderSn, dataBean.getOrder_sn()));
                if (adjustmentOrder2 != null) {
                    continue;
                }
                //定义查询参数
                AdjustmentOrderVo adjustmentOrderVo = new AdjustmentOrderVo();
                adjustmentOrderVo.setOrderSn(dataBean.getOrder_sn());//调整单号
                if (dataBean.getStatus() != 20) {
                    continue;
                }
                //仓库ware_house_name
                Warehouse wid = warehouseMapper.selectOne(Wrappers.lambdaQuery(Warehouse.class)
                        .eq(Warehouse::getName, dataBean.getWare_house_name()));
                Assert.notNull(wid, "仓库不存在");
                if (wid != null) {
                    adjustmentOrderVo.setWid(wid.getId());
                }
                if (dataBean.getType() == 0) {
                    adjustmentOrderVo.setType("0");
                } else if (dataBean.getType() == 1) {
                    adjustmentOrderVo.setType("1");
                }
                adjustmentOrderVo.setRemark(dataBean.getRemark());
                adjustmentOrderVo.setStatus("5"); //状态
                List<AdjustmentOrderProductItemVo> productLists = new ArrayList<>();
                for (int j = 0; j < dataBean.getItem_list().size(); j++) {
                    adjustmentOrder.DataBean.ItemListBean itemListBean = dataBean.getItem_list().get(j);
                    AdjustmentOrderProductItemVo adjustmentOrderProductItemVo = new AdjustmentOrderProductItemVo();
                    Product sku = productMapper.selectOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, itemListBean.getSku()));
                    Assert.notNull(sku, itemListBean.getSku() + "产品不存在");
                    adjustmentOrderProductItemVo.setSku(itemListBean.getSku());
                    adjustmentOrderProductItemVo.setPrdName(sku.getId());
                    adjustmentOrderProductItemVo.setPicUrl(sku.getPicUrl());
                    //设置仓位
                    List<com.fowo.api.service.handleWork.jindieEntity.adjustmentOrder.DataBean.ItemListBean.ToAvailableBinListBean> toAvailableBinList = itemListBean.getTo_available_bin_list();
                    String whbCode = toAvailableBinList.get(0).getWhb_code();
                    WarehouseBin warehouseBin = warehouseBinService.getOne(Wrappers.lambdaQuery(WarehouseBin.class)
                            .eq(WarehouseBin::getWarehouseId, wid.getId())
                            .eq(WarehouseBin::getStorageBin, whbCode));
                    Assert.notNull(warehouseBin, whbCode + "仓位不存在");
                    adjustmentOrderProductItemVo.setGoodWarehouseBin(warehouseBin.getId());
                    adjustmentOrderProductItemVo.setNewGoodWhb(warehouseBin.getId());
                    //adjustmentAmount  adjustment_valid_num 调整量
                    adjustmentOrderProductItemVo.setAdjustmentAmount(itemListBean.getAdjustment_valid_num());
                    //原店铺
                    if (!StringUtils.isEmpty(itemListBean.getSeller_name())) {
                        ShopInfo shop = shopInfoService.getOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getShopName, itemListBean.getSeller_name()));
                        Assert.notNull(shop, itemListBean.getSeller_name() + "店铺不存在");
                        if (shop != null) {
                            adjustmentOrderProductItemVo.setShop(shop.getId());
                        }
                        //原fnsku
                        if (!StringUtils.isEmpty(itemListBean.getFnsku())) {
                            List<ListingFather> list = listingFatherServiceImpl.list(Wrappers.lambdaQuery(ListingFather.class)
                                    .eq(ListingFather::getFnsku, itemListBean.getFnsku())
                                    .eq(ListingFather::getShop, shop.getId())
                            );
                            Assert.isTrue(list.size() > 0, itemListBean.getFnsku() + "fnsku不存在");
                            adjustmentOrderProductItemVo.setFnsku(list.get(0).getId());
                            adjustmentOrderProductItemVo.setFnskuName(itemListBean.getFnsku());
                            adjustmentOrderProductItemVo.setFnskuFnsku(itemListBean.getFnsku());
                        }
                    }
                    //出库
                    if (!StringUtils.isEmpty(itemListBean.getTo_seller_name())) {
                        ShopInfo shop = shopInfoService.getOne(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getShopName, itemListBean.getTo_seller_name()));
                        Assert.notNull(shop, itemListBean.getTo_seller_name() + "店铺不存在");
                        if (shop != null) {
                            adjustmentOrderProductItemVo.setNewShop(shop.getId());
                        }
                        //原fnsku
                        if (!StringUtils.isEmpty(itemListBean.getTo_fnsku())) {
                            List<ListingFather> list = listingFatherServiceImpl.list(Wrappers.lambdaQuery(ListingFather.class)
                                    .eq(ListingFather::getFnsku, itemListBean.getTo_fnsku())
                                    .eq(ListingFather::getShop, shop.getId())
                            );
                            Assert.isTrue(list.size() > 0, itemListBean.getFnsku() + "fnsku不存在");
                            adjustmentOrderProductItemVo.setNewFnsku(list.get(0).getId());
                            adjustmentOrderProductItemVo.setNewFnskuName(itemListBean.getTo_fnsku());
                            adjustmentOrderProductItemVo.setNewFnskuFnsku(itemListBean.getTo_fnsku());
                        }
                    }
                    productLists.add(adjustmentOrderProductItemVo);
                }
                adjustmentOrderVo.setProductLists(productLists);
                adjustmentOrderService.create(adjustmentOrderVo);
            }
        }

    }

    public void saveClassify(JSONArray result) {
        if (Objects.isNull(result)) {
            return;
        }
        for (Object t : result) {
            JSONObject o = (JSONObject) t;

            ClassifyVo vo = new ClassifyVo();
            vo.setId(o.getLong("cid"));
            vo.setParentId(o.getLong("parent_cid"));
            vo.setName(o.getString("title"));
            try {
                classifyService.create(vo);
            } catch (Exception e) {
                log.error("创建期初库存失败", e);
            }
        }
    }
}
